调用者无法看到函数返回的char数组字符串

时间:2011-11-26 06:38:10

标签: c

我从函数返回一个char指针。但调用者无法看到字符串。

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);

}

这是来电者。输出为空。

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

char* msg = getFileContent(imagefile);

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

free(msg);

return 0;
}

请帮忙。

2 个答案:

答案 0 :(得分:1)

错误在于:

printf("Output:", msg);

你不打印字符串。试试这个:

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

需要%s告诉printf()msg打印为字符串。


请注意,由于缓冲,您可能还需要添加\n

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

这是另一个小错误:

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

应该是:

message[len] = '\0';

答案 1 :(得分:0)

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

我不确定是否可以保证在缓冲区buf分配后它无效。因此,读取后buf [len]可能不是'\ 0',如果读取文本中没有'0 \'那么你的strcpy可能会超出其边界。所以要么使用strncpy,要么将上面两行改为

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

此外,第一个版本将'\ 0'置于len + 1,在我看来是假的。想象一下,你已经读取了0个字节,然后len = 0,而消息[1]被设置为'\ 0',这使得消息[0]未定义。

可能你的代码运行正常,因为有一个创建更改,分配的缓冲区buf用零填充或者你的编译器主动使它无效。但据我所知,对于C编译器来说,这不是强制性的。