[C language] memory management

memory management

  • calloc(): Dynamically allocate num continuous spaces of long size, each byte is initialized to 0: that is, a memory space of num*size bytes of length is allocated, and the value of each byte is 0
    • void *calloc(int num, int size);
  • malloc(): The heap area allocates a memory space of a specified size to store data, not initialized, and its value is unknown
    • void *malloc(int num);
  • free(): Release the memory block pointed to by address and release the dynamically allocated memory space
    • void free(void *address);
  • realloc(): Reallocate memory, expand memory to newsize
    • void *realloc(void *address, int newsize);

void *: Pointer of undetermined type, C, C++ can be cast to other type pointers by casting

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char name[100];
    char *description;
    strcpy(name, "Zara Ali");
    description = (char*)malloc(200*sizeof(char));  //  分配内存
    description = (char*)calloc(200,sizeof(char));
    description = (char*)realloc(description, 100*sizeof(char));    //  重新分配内存
    free(description);  //  释放内存
}

Guess you like

Origin blog.csdn.net/weixin_46143152/article/details/126688351