Proper usage of realloc()

Just don’t call free() on your original ptr in the happy path. Essentially realloc() has done that for you. ptr = malloc(sizeof(int)); ptr1 = realloc(ptr, count * sizeof(int)); if (ptr1 == NULL) // reallocated pointer ptr1 { printf(“\nExiting!!”); free(ptr); exit(0); } else { ptr = ptr1; // the reallocation succeeded, we can overwrite our original … Read more

Difference between malloc and calloc?

calloc() gives you a zero-initialized buffer, while malloc() leaves the memory uninitialized. For large allocations, most calloc implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX mmap(MAP_ANONYMOUS) or Windows VirtualAlloc) so it doesn’t need to write them in user-space. This is how normal malloc gets more pages from the OS … Read more

tech