KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
What does malloc(0) return? Would the answer be same for 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; } Output from Linux GCC: manav@manav-workstation:~$ gcc -Wall mal.c manav@manav-workstation:~$ ./a.out 0x9363008 (nil) manav@manav-workstation:~$ The output keep changing everytime for malloc(0) . Is this a standard answer? And why would anyone be interested in getting such a pointer, other than academic research? EDIT: If malloc(0) returns dummy pointer, then how does following works: int main() { void *ptr = malloc(0); printf("%p\n", realloc(ptr, 1024)); return 0; } EDIT: The following code outputs "possible" for every iteration. Why should it not fail ? #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", i); else { printf("Failed for iteration %d\n", i); break; } } return 0; }
Tags (comma-separated)
Save Edits
Cancel