memory corruption

前端 未结 7 1036
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 19:31

i was running a small c program:

#include
int main()
{
char *p;
p = (char *)malloc(10);
free(p);
free(p);
free(p);
printf(\"\\npointer is freed!!\         


        
相关标签:
7条回答
  • 2021-01-21 20:01

    There are multiple issues with your program:

    1. Since you're using malloc() and free(), you should do #include <stdlib.h> before calling any of those functions.
    2. There's no need to cast the return value from malloc(): it returns a void *, which can be assigned to any other pointer type safely (except function pointers). So, you can do: p = malloc(10);
    3. Once you free a pointer allocated by malloc() or realloc(), using the pointer value in any way is bad: in particular, you cannot call free() on it again.
    4. int main() is better written as int main(void).
    5. Since main() returns int, you should return a value from it. Traditionally, 0 means success.

    Of course, the main (no pun intended) problem with your program is freeing it many times, but other issues mentioned above are important too. Once you've free()'d a pointer successfully, calling free() on it is undefined behavior: the program can do anything, including (unfortunately), seeming to not do anything bad. I say "unfortunately" because it might give you a sense of security that it's okay to free() a pointer more than once.

    0 讨论(0)
提交回复
热议问题