function returns address of local variabe
const char * read() {
FILE *fp;
char buff[256];
fp = fopen("/sys/class/net/enp1s0/statistics/rx_bytes", "r");
fgets(buff, 256, (FILE*)fp);
fclose(fp);
return buff;
}
int main(){
const char* server_message = read(); //returns null here
}
The question is: how to assign the buuf's value to server_message variable
Thanks
readfunction does not return null. Rather, it returns an invalid address. If you want to return a valid address, you should allocate space for buff.NULL. Instead an address is returned that is illegal to access after the function returns.buffvariable static, but that's considered bad style for a number of reasons. Or you allocate the result dynamically and the caller has to free it.char buff[256]is only local and available inside of the functionread. The memory is deallocated at the end of the function, so when you return it, it ends up as undefined behaviour.