简体   繁体   中英

Why realloc with size '0' allows to free the pointer multiple times but not malloc with size '0'?

I have the following code.

char *ptr2 = (char*)malloc(0);
char *ptr = (char*)malloc(sizeof(char) * 10);
memcpy(ptr, "Gunasek\0", 8);
ptr = (char*) realloc(ptr, 0);
printf("ptr = %p, ptr2 = %p\n", ptr, ptr2);
//ptr = (nil), ptr2 = 0x602420       (Output)
free(ptr);
free(ptr);//Works fine
free(ptr);//Works fine

free(ptr2);
free(ptr2);//Fails
free(ptr2);

Could anyone explain why malloc(0) doesn't allow for free more than once but realloc(ptr, 0) does?

Freeing a non-null pointer more than once is undefined behaviour (whether it came from malloc or realloc ). Understanding why your particular implementation behaves the way it does is therefore unhelpful. It would also be dangerous to rely on this behaviour since it could change in the future or even in a different context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM