Memory Allocation in C
The malloc function prototype is : void* malloc(size_t size); This function will allocates a block of size bytes of memory, returning a pointer to the beginning of the block. Attention: this function is only for allocating memory! So the initial value of these memory will be Non-Zero. Maybe sometimes, it will be zero. Code for example:
1 | #include<stdio.h> |
The realloc function prototype is : void* realloc(void* ptr, size_t size); This function will reallocates a block of size bytes of memory, returning a pointer to the beginning of the block. If size is zero and ptr is not NULL, it will be used as free(). If prt is NULL and size is not zero, it will be used as malloc(). If ptr is NULL and size is zero, return value is some kind of memory which contains zero elements! Wooo~~~~. Look at the following codes:
1 | char * p = NULL; |
why?! Because if this function is called successfully, it will return non-zero memory address. And you will see the third output subtract the second output will be 16 bytes. If ptr is not NULL , and size is non-zero, and current block can simply expand without moving, the return value is the same as ptr. But there is not enough space for simply expand, it will execute free(ptr) and return malloc(size). This function will become very dangerous!
1 | char * k = (char*)realloc(NULL,100); |
Safety called will be like the following:
1 | char * k = (char*)realloc(NULL,100); |
If there is not enough free memory to be allocated, this function will return NULL.Attention: this function will not initialize those memory also.
calloc's prototype is void* calloc(int num, size_t size).
1 | char* p = (char*)calloc(20,sizeof(char)); |
But calloc is efficient!
free function is to delete memory which has been allocated. But free function will not assign the point to zero.
1 | char * p = (char*)calloc(100); |
And all of those functions will not recommend to be used in c++, because those functions will not initialize class structure or v_ptr. free() function will not destruct parent class when sub class is destructed. In c++, maybe should always use new and delete!