简体   繁体   中英

Caller cannot see the char array string returned from a function

I am returning a char pointer from a function. But the caller is unable to see the string.

char* getFileContent(char* file)
{

FILE* fp = fopen("console.txt", "r");

fseek(fp, 0L, SEEK_END);
size_t sz = ftell(fp);
fseek(fp, 0L, SEEK_SET);


char* message = (char*)malloc(sz+1);
char buf[sz+1];

size_t len = 0;
if (fp != NULL)
{
    len = fread(buf, sizeof(char), sz, fp);
}

printf("MALLOC SIZE:%d FILE SIZE:%d", sz, len);

strcpy(message,buf);    //Modified code. This line fixed the code
message[++len] = '\0';
//printf("MESSAGE:%s", message);

return(message);

}

This is the caller. Output is empty.

int main(int argc, char **argv, char **env)
{

char* msg = getFileContent(imagefile);

if(msg != NULL)
    printf("Output:%s \n", msg);

free(msg);

return 0;
}

Please help.

The error is here:

printf("Output:", msg);

You're not printing the string. Try this instead:

printf("Output: %s", msg);

The %s is needed to tell printf() to print msg as a string.


Note that due to buffering, you may also need to add a \\n :

printf("Output: %s \n", msg);

Here's another minor error:

message[++len] = '\0';

should be:

message[len] = '\0';
strcpy(message,buf);    //Modified code. This line fixed the code
message[++len] = '\0';

I'm not sure if it is guaranteed that after the allocation of the buffer buf it is nullified. Therefore buf[len] might not be '\\0' after reading and if there is no '0\\' in the read text then your strcpy might run outside its bounds. So either use strncpy or change the above two lines into

buf[len++] = '\0\;
strcpy(message,buf);

Also the first version places the '\\0' at len+1 which in my opinion is false. Imagine you've read 0 bytes then len=0 and message[1] is set to '\\0' which leaves message[0] undefined.

Probably your code just ran fine because there is a create change the the allocated buffer buf is either filled with zeros or your compiler actively nullifies it. But as far as I know this is not mandatory for C compilers todo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM