Realloc Function, Free Function, Dangling Pointers in C - 1623996352339
Realloc Function, Free Function, Dangling Pointers in C - 1623996352339
Another Example:
Output:
realloc() function in C:
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory
by realloc() function. In short, it changes the memory size.
Ptr=realloc(ptr, new-size)
For Example:
Output:
free() function in C:
free(ptr)
Dangling pointers in C:
Dangling pointer occurs at the time of the object destruction when the object is
deleted or de-allocated from memory without modifying the value of the pointer.
In this case, the pointer is pointing to the memory, which is de-allocated. The
dangling pointer can point to the memory, which contains either the program
code or the code of the operating system. If we assign the value to this pointer,
then it overwrites the value of the program code or operating system
instructions; in such cases, the program will show the undesirable result or may
even crash.
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr=(int *)malloc(sizeof(int));
5. int a=890;
6. ptr=&a;
7. free(ptr);
8. return 0;
9. }
If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted
memory. Therefore, we can say that ptr is not a dangling pointer, as shown in
the below image: