什么malloc(0)
回报?答案是否相同realloc(malloc(0),0)
?
#include<stdio.h>
#include<malloc.h>
int main()
{
printf("%p\n", malloc(0));
printf("%p\n", realloc(malloc(0), 0));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
linux gcc的输出:
manav@manav-workstation:~$ gcc -Wall mal.c
manav@manav-workstation:~$ ./a.out
0x9363008
(nil)
manav@manav-workstation:~$
Run Code Online (Sandbox Code Playgroud)
输出每次都在变化malloc(0)
.这是标准答案吗?除了学术研究之外,为什么有人会对获得这样的指针感兴趣?
编辑:
如果malloc(0)
返回虚拟指针,那么后续工作原理如何:
int main()
{
void *ptr = malloc(0);
printf("%p\n", realloc(ptr, 1024));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
以下代码为每次迭代输出"可能".为什么不失败?
#include<stdio.h>
#include<malloc.h>
int main()
{
int i;
void *ptr;
printf("Testing using BRUTE FORCE\n");
for (i=0; i<65000; i++)
{
ptr = malloc(0);
if (ptr == realloc(ptr, 1024))
printf("Iteration %d: possible\n", …
Run Code Online (Sandbox Code Playgroud)