简体   繁体   English

为什么大小为“0”的 realloc 允许多次释放指针但不允许大小为“0”的 malloc?

[英]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?谁能解释为什么malloc(0)不允许多次免费但realloc(ptr, 0)允许?

Freeing a non-null pointer more than once is undefined behaviour (whether it came from malloc or realloc ).多次释放非空指针是未定义的行为(无论它来自malloc还是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.依赖这种行为也很危险,因为它可能会在未来甚至在不同的环境中发生变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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