When a program requests memory from the heap, it is given a pointer to the starting address of that memory block. When the program frees that memory block, the memory is returned to the heap and the pointer is no longer valid.
Using freed heap memory can result in undefined behavior and potentially cause serious problems in a program.
If the program tries to access the memory through that pointer after it has been freed, it can lead to several issues such as:
To avoid these issues, it's important for developers to properly manage memory in their programs by deallocating memory only when it's no longer needed and avoiding accessing freed memory.
int* mem = (int*)malloc(sizeof(int));
*mem = 10;
if (rand() % 10 == 0) {
free(mem);
}
printf("%d", *mem); // possible use after the pointer has been freed