A
arnuld
Here is what I have made a small program to gain the understanding of
malloc() and free(). I malloc() some memory, assign some value to it and
then free() it but I got Segfault whne I try to free() the
malloc()ed memory:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int x = 3;
int* px = malloc( 1 * sizeof(*px));
int* p2 = malloc( 1 * sizeof(*p2));
if( (NULL == px) || (NULL == p2) )
{
printf("malloc() failed\n");
}
px = &x;
p2 = px;
printf("x = %d\n", x);
printf("*px = %d\n", *px);
printf("*p2 = %d\n", *p2);
printf("&x = %p\n", (void*)&x);
printf("px = %p\n", (void*)px);
printf("p2 = %p\n", (void*)p2);
free(p2);
p2 = NULL;
printf("-------------- p2 freed and set NULL ---------------------------\n\n");
printf("x = %d\n", x);
printf("*px = %d\n", *px);
printf("&x = %p\n", (void*)&x);
printf("px = %p\n", (void*)px);
printf("p2 = %p\n", (void*)p2);
free(px);
px = NULL;
return 0;
}
================ OUTPUT =======================
[arnuld@dune programs]$ gcc -std=c99 -pedantic -Wall -Wextra test.c
[arnuld@dune programs]$ ./a.out
x = 3
*px = 3
*p2 = 3
&x = 0xbfee8e04
px = 0xbfee8e04
p2 = 0xbfee8e04
Segmentation fault
[arnuld@dune programs]$
malloc() and free(). I malloc() some memory, assign some value to it and
then free() it but I got Segfault whne I try to free() the
malloc()ed memory:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int x = 3;
int* px = malloc( 1 * sizeof(*px));
int* p2 = malloc( 1 * sizeof(*p2));
if( (NULL == px) || (NULL == p2) )
{
printf("malloc() failed\n");
}
px = &x;
p2 = px;
printf("x = %d\n", x);
printf("*px = %d\n", *px);
printf("*p2 = %d\n", *p2);
printf("&x = %p\n", (void*)&x);
printf("px = %p\n", (void*)px);
printf("p2 = %p\n", (void*)p2);
free(p2);
p2 = NULL;
printf("-------------- p2 freed and set NULL ---------------------------\n\n");
printf("x = %d\n", x);
printf("*px = %d\n", *px);
printf("&x = %p\n", (void*)&x);
printf("px = %p\n", (void*)px);
printf("p2 = %p\n", (void*)p2);
free(px);
px = NULL;
return 0;
}
================ OUTPUT =======================
[arnuld@dune programs]$ gcc -std=c99 -pedantic -Wall -Wextra test.c
[arnuld@dune programs]$ ./a.out
x = 3
*px = 3
*p2 = 3
&x = 0xbfee8e04
px = 0xbfee8e04
p2 = 0xbfee8e04
Segmentation fault
[arnuld@dune programs]$