C Language memory allocation is simple: malloc, calloc, realloc, free
malloc (number of bytes); Returns the first address of the memory segment, void.
Calloc (number, type size); The difference with malloc is that it initializes the memory to be empty.
ReAlloc (original pointer, number of bytes); Reallocation of memory allocated by malloc, calloc; There are too many things to note here:
1, if reduced, will cut off a piece, will retain the previous content;
2, if expanded, will still retain existing content, but the new memory will not initialize;
3, in the expansion, it is possible that the memory address will change, so that the original pointer will be discarded, but the return value is a new pointer, so continue to use should be the return value.
If the allocation fails, it returns NULL, typically because of insufficient memory; Allocating 0 bytes of memory also returns NULL but that doesn't make sense.
They are all freed with free (pointers).
1. Allocate memory to an integer:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p = NULL;
// p = malloc(sizeof(int)); /* 应该像下一句同时类型转换, 不然在 C++ 里面不行 */
p = (int *)malloc(sizeof(int));
*p = 100;
printf("%d\n", *p);
free(p);
getchar();
return 0;
}
2. Allocate memory to 3 integers:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p = NULL;
p = (int *)malloc(sizeof(int)*3);
*p = 111;
*(p+1) = 222;
*(p+2) = 333;
printf("%d,%d,%d\n", *p, *(p+1), *(p+2));
free(p);
getchar();
return 0;
}