🌑

Hello, friends!

Dynamic resource allocation in C++

#include<stdlib.h>

malloc

malloc allocate length of n blocks in the heap

malloc(int size);

malloc(100) // allocate 100 byte in the heap
  • return of malloc is a pointer with untype void *,
  • if you want to use for other type, it should do like this :
int *p=(int *)malloc(1)
// p is the pointer, allocate 1 byte in the heap

// however, if we want to store value 1 in the *p, since int is 4 byte, there are 3 byte is lost. to solve the problem, please use this :

int *p=(int *)malloc(sizeof(int)*100);
// in this way, allocate 100 int space in the heap, so it can store 100 integer.
  • if success, it will return the pointer (point to the beginning), otherwise, return the NULL pointer
  • we need to use if statement to test before following other process.
  • 这个内存分配在逻辑上是连续的,物理上可以不连续的,但是我们只需要关注逻辑上即可

free release the space

when we don’t use the space that we allocated using malloc, we need to release the space.

// void free(void *ptr)

int *p=(int *)malloc(sizeof(int)*5);

free(p)
  • there is no return in the function.
  • if pointer is NULL, the function would not process any thing.

realloc change the size of the memory block pointed by ptr

void *realloc(void * ptr, size_t size)
  • ptr is the pointer of the memory block, size is the new desired size of the memory
  • if the new block size < older one, the memory allocation will be depend on the OS
    • totally change to the new size, excess memory will be released
    • memory fragment
  • if the new block size > older one :
    • extend the existing block (if there are enough continuous space )
    • move to the new block that larger in the memory . it will copy the content to the new one. (address change)
int *p=(int *)malloc(sizeof(int)*10);

int *a=(int *)realloc(p,sizeof(int)*20);
if (a==p){
	printf("there is no change in the address");
}
else{
	printf("there is change in the address");
}

— Feb 22, 2024

Search