If the allocated memory is not released or de-allocated, it causes a memory leak. /* Function with memory leak because programmer forgot to release dynamically allocated memory */
#include<stdlib.h>
void f()
{ int *ptr =(int*) malloc(10*sizeof(int));
/* Do some work */
return; /* returns without freeing ptr*/
}
/* Function without memory leak because memory freed by programmer when no longer needed*/
#include<stdlib.h>
void f()
{ int *ptr =(int*) malloc(10*sizeof(int));
/* Do some work */
free (ptr):
return;
}
A dangling pointer points to a memory location that has already been freed. If we try to access the memory location using the pointer it causes a segmentation fault.
/* Function without memory leak */
#include<stdlib.h>
void f()
{
int *ptr =(int*) malloc (sizeof(int))
*ptr = 10; //valid
*free (ptr):
**ptr = 20; // invalid because here ptr is dangling pointer.
return;
}
Also Read
- Static and Dynamic Memory Allocation
- Memory Allocation for 2D Array
- Dynamic Memory Allocation
- Pointer constant and constant pointer
- Some Pointer Declaration and their Meanings
- Function and pointers
- Initializing Pointer to Pointer
- Pointer to Pointer Multiple Indirection
- Relationship between Arrays and Pointers
- Pointer to Array
- Pointer Arithmetic
- Types of Pointers
- Illustrate Basic Pointer Use
- Using Pointer
- Intializing Pointer
- Declaring Pointer
- Application of Pointers
- Value Model VS Reference Model
- What is Pointer
Comments
Post a Comment
Please give us feedback through comments