zero size malloc [duplicate]

The behaviour is implementation defined, you will receive either a NULL pointer or an address. Calling free for the received pointer should however not cause a problem since: free(NULL) is ok, no operation is done free(address) is ok, if address was received from malloc (or others like calloc etc.)

What is C++ version of realloc(), to allocate the new buffer and copy the contents from the old one?

There’s no new/delete equivalent of realloc in C++. From Bjarne Stroustrup’s FAQ : Why doesn’t C++ have an equivalent to realloc()? If you want to, you can of course use realloc(). However, realloc() is only guaranteed to work on arrays allocated by malloc() (and similar functions) containing objects without user-defined copy constructors. Also, please remember … Read more

Is typecast required in malloc? [duplicate]

I assume you mean something like this: int *iptr = (int*)malloc(/* something */); And in C, you do not have to (and should not) cast the return pointer from malloc. It’s a void * and in C, it is implicitly converted to another pointer type. int *iptr = malloc(/* something */); Is the preferred form. … Read more

Malloc and array index confusion in C

C doesn’t enforce any array bounds checking, so while you requested space for 5 integers, you used more. In fact you overwrote 4 memory locations that really weren’t set aside for your specific purpose. Your program went past the area in memory that was set aside for your array, and started to store values in … Read more

Variable Sized Arrays vs calloc in C

If you declare int array[variable] the memory will be allocated on the stack which is not very good for large, relatively permanent data structures (such as one you might want to return). You don’t need to free memory manually if you use the array syntax since it’s freed when it goes out of scope. calloc … Read more

Why does malloc allocate a different number of bytes than requested?

First, Malloc makes no guarantees that two successive malloc calls return successive pointers. Second, depending on your specific architecture, different alignment rules apply; sometimes you might ask for a single byte, but the architecture prefers allocations on 8- or 4-byte intervals. Third, malloc needs some overhead to store how big the allocated block is, etc. … Read more