Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

malloc, calloc and realloc

Status
Not open for further replies.

mattias1975

Programmer
Jul 26, 2004
36
SE
Hello!

What is the differenc betwen malloc, calloc ond realloc?
The only thing i know is that malloc is used for alocating memory.
I have a bug in my code. The first time i use malloc everything works. But the next time at the same row the program "hangs up" at the point where i am calling the malloc. Whats wrong?
I am freeing the memory with free(). Should i use calloc or realloc instead?

Thank you
 
Code:
void *malloc( size_t size );
void *calloc( size_t num, size_t size );
void *realloc( void *memblock, size_t size );
All three functions in principle do the same work. Differences are:
1. calloc() allocates num*size bytes and initializes this memory chunk with zeroes (malloc() returns a pointer to undefined contents).
2. realloc() may deallocate memory if size == 0 and saves previous contents of reallocated memory chunk if memblock != 0 and size > 0). Be careful: realloc() may return different pointer (and an old value of memblock is now undefined in that case).

So, no valuable differences in this mechanics and you may mix these three function calls as you wish (don't forget free() returned pointers;). You never should, you may if you wish...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top