Is this a double free in C?

☆樱花仙子☆ 提交于 2019-12-01 06:02:19

问题


Normally, if a pointer is freed twice, it's a double free. For example,

char *ptr;
ptr=malloc(5 * sizeof(*ptr));
free(ptr);
free(ptr);

The above code is considered as double free. Is the following considered as double free as well?

char *ptr;
char *ptr1;
ptr=malloc(5 * sizeof(*ptr));
ptr1=ptr;
free(ptr);
free(ptr1);

Thank you.


回答1:


Yes. The library doesn't care what name you gave a varaible in your source code (it's long gone by the time the code is executed). All that matters is the value, and in this case the values passed to free() would be the same.




回答2:


Yes. You're freeing the same memory twice.




回答3:


Yep. A double free is when you attempt to free a memory block that has already been freed. Both ptr and ptr1 are pointing to the same memory block, so the second call to free is attempting to free a memory block that is already freed.




回答4:


Yes as the pointers both point to the same address and so pass the same address to free.

You can show what the value of the pointer is by printing it

printf( "%p", ptr);

or look at it in a debugger




回答5:


Yes this is a double free (and a very bad thing to do). The ptr1 is a pointer to the memory allocated by the malloc. It is the same location that ptr was pointing to. By freeing ptr and ptr1 you are freeing the same memory twice.



来源:https://stackoverflow.com/questions/3389750/is-this-a-double-free-in-c

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