开发者

Do I have to free memory from every initialized string?

开发者 https://www.devze.com 2023-04-09 11:34 出处:网络
// loads a file into memory void load_file() { char *data = \"This is so data\"; printf(\"function: %s\\n\", data);
// 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

精彩评论

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