开发者

Do I have to free memory from every initialized string?

// loads a file into memory
void load_file()
{
   char *data = "This is so data";
   printf("function: %s\n", data);

}

Will the above code leak memory? Do I have call free(data)? Why o开发者_JAVA技巧r why not?


It cannot leak because you did not dynamically allocate it. data is a string literal and not a dynamically allocated array of characters.


You don't allocate any memory there, so no memory is getting leaked. You are simply copying a pointer to an existing string in the executable image, not the string itself.

For that reason, the type of data should be const char* to prevent accidental changes to the string to which data points.

data itself, a pointer, is allocated on the stack, just like i in int i = 5; would be. That kind of implicit allocation is de-allocated automatically too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜