Is there any harm in calling 'free' for the same pointer twice in a C program?

后端 未结 4 1517
天命终不由人
天命终不由人 2021-01-04 10:44

If I have a c program, like:

SomeTypePtr my_type;
my_type = malloc(sizeof(someType));

/* do stuff */

free(my_type);

/* do a bunch of more stuff */

free(m         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 11:00

    1. It will not make your pointer NULL.
    2. It will free the memory pointed by the pointer, leaving the pointer set to an unallocated segment of memory.
    3. If you don't use malloc or calloc between the calls it will give you a Segmentation Fault.
    4. "Best practice is that a pointer passes out of scope immediately after being freed." means that the pointer should stay on the stack so that it should not be set NULL explicitly because it will eventually go out of scope and be freed.

提交回复
热议问题