Free an assigned pointer

最后都变了- 提交于 2020-01-02 01:07:12

问题


Does the following code free the memory that was allocated for x?

int main()
{
    char *x = (char*)calloc(100, sizeof(char));
    char *y = x;
    free(y);
}

回答1:


Yes

When you do

char *y = x;

you make y point to the location where x points to. Since y points to a memory location returned by calloc,

free(y);

is perfectly valid. As @haccks commented, this would not work if you make y point to another memory location, provided that this memory location wasn't returned by malloc/calloc/realloc.


In C, you should not cast the result of malloc/calloc/realloc. Also, checking the return value of calloc to see if it was successful is good. calloc will return NULL on failure.




回答2:


The original version of the question had

int *y = x;
free(y);

I.e. assigning the char pointer to an int pointer and then invoke free() on the int pointer. The signature of free() is void free(void *ptr); so irrespective of char * vs. int *, memory would be released.

The edited (and current) version of the question has

char *y = x;
free(y);

Here, both y and x points to the same memory. This is known as pointer aliasing. Upon the call to free(), that memory would certainly be released.

A problem, however, is that after free(y), the pointer x would be dangling, i.e. the memory it is pointing to is no longer valid.

Note, it is neither necessary nor recommended to cast the return value from calloc.




回答3:


Yes, it does.

The method is void free(void *ptr), then when you make char* y = x, you have a pointer to the same space memory that y was pointing.

That let you free that space later with free (y).

However, you would put x = NULL because now x doesn't have a own space despite it have a value.

For further information about free read here.




回答4:


The memory returned by your call of calloc() is released by the call of free().

In your code that affects both x and y.



来源:https://stackoverflow.com/questions/29985497/free-an-assigned-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!