Hey Guys,
I wanted to allocate dynamic memory for multiple variables and assign values to memory locations.
I allocated memory for three variables, then allocated memory for two variables and then freed allocated memory.
Output = 10 10
I don't understand why the value is stored even after the memory is freed ?
I wanted to allocate dynamic memory for multiple variables and assign values to memory locations.
I allocated memory for three variables, then allocated memory for two variables and then freed allocated memory.
C:
#include<stdio.h>
#include<stdlib.h>
int main ()
{
// Memory allocate for 3 variables
int *var = malloc(3* sizeof(int));
if ( var != NULL )
{
var[0] = 10;
var[1] = 3;
var[2] = 9;
}
// memory allocate for more two variables,
//total memory allocated for five variables
var = realloc(var, 5 * sizeof(int)) ;
if ( var != NULL )
{
var[3] = 9;
var[4] = 5;
printf(" %d", *var);
}
free(var);
printf(" %d", *var);
return 0;
}
I don't understand why the value is stored even after the memory is freed ?