C language dynamic memory allocation

  • 2020-05-26 09:52:33
  • OfStack

C language dynamic memory allocation

1. Why use dynamic memory allocation

Arrays can waste memory when used, and dynamic memory allocation can solve this problem.

2. malloc and free

The C library provides two functions, malloc and free, for performing dynamic memory allocation and freeing, respectively.

(1) void *malloc(size_t size);

The parameter of malloc is the number of bytes of memory to be allocated. malloc allocates 1 contiguous block of memory. If the operating system cannot provide more memory to malloc, malloc returns an NULL pointer.

(2) void free(void *pointer);

The argument to free is either NULL or a value previously returned from malloc, calloc, or realloc.

3. calloc and realloc

(1) void *calloc(size_t num_elements,size_t element_size);

calloc is also used for memory allocation. The main difference between malloc and calloc is that the latter initializes it to 0 before returning a pointer to memory.

(2) realloc(void *ptr,size_t new_size);

The realloc function modifies the size of a previously allocated block of memory. If it is used to expand 1 memory, the original contents of this memory will still be retained, and the new memory will be added after the original memory block. If it is used to shrink a block of memory, part of the memory at the end of the block is removed and the original contents of the rest of the memory remain.

4. Use dynamically allocated memory

(1) use examples

int *pi;

pi = malloc(25 * sizeof(int));

if(pi == NULL){

printf("out of memery\n");



(2) use indirect access

int *pi2,i;

pi2 = pi;

for(i = 0;i < 25;i += 1)

*pi2++ = 0;

You can also use subscripts.

int i;

for(i = 0;i < 25;i += 1)

*pi[i] = 0;

5. Common dynamic memory errors

Common errors include de-referencing the NULL pointer, operating on allocated memory over a boundary, freeing memory that is not allocated, trying to free a portion of a block of dynamically allocated memory, and continuing to use a block of dynamically allocated memory after it has been freed.

The above is the C language dynamic memory allocation information explanation, if you have any questions please leave a message or to the site community discussion, thank you for reading, hope to help you, thank you for the support of the site!

Related articles: