Hi!
I am new in C. I try to use dynamical allocation fuction malloc( ) and
realloc( ).
I found something strange.
After several calling realloc( ), the malloc( ) will give me a
Segmentation fault.
If I just call realloc( ) once before calling malloc( ), it is OK.
Why?
I am trying to read some double-typed items from infile and save them
to c_buf[i].
Only when reaching EOF then I know the num_of_item = 50 (in
infile).
In the following codes at the bottom
If I use initial value size_for_n = 60, my code is ok
but if I size_for_n = 10 as initial value,
I will have Segmentation fault later when I call malloc().
I am using GCC on Linux machine.
My code is :
int num_of_item = 0;
int size_for_n = 10 ;
// int size_for_n = 60 OK, size_for_n = 10 is NG ;
fprintf (stderr,"Allocating memory for c_buf[%d]\n",size_for_n);
c_buf = ( double * ) malloc( size_for_n * sizeof(double));
if ( c_buf == NULL ) {
fprintf (stderr,
"Could not allocate memory for c_buf[%d]\n",size_for_n);
goto TERMINATE;
};
while(! EOF )
{
num_of_item++;
read_one_more_item(infile);
if ( num_of_item > size_for_n) ) {
size_for_n *= 2;
c_buf = ( double * )
realloc( (void *)c_buf, size_for_n * sizeof(double));
fprintf (stderr,
"Trying to re-allocating memory for
c_buf[%d]!\n",size_for_n);
if ( c_buf == NULL ) {
fprintf (stderr,
"Re-allocating memory for c_buf[%d]
fails!\n",size_for_n);
goto TERMINATE;
};
}
}
global_n = num_of_item;
// reallocating exact memory to c_buf[ ]
c_buf = ( double * ) realloc( (void *)c_buf, global_n *
sizeof(double));
fprintf (stderr,
"Finalizing in re-allocating memory for c_buf[%d]!\n",global_n
);
if ( c_buf == NULL ) {
fprintf (stderr,"Re-allocating memory for c_buf[%d]
fails!\n",global_n );
exit(-1);
}
....
....(codes omited)
int *p_int ; // local
....
global_m = 9000.
// global_m's value is derived in the (codes omited) part
above
fprintf (stderr,"Assigning memory.\n");
fprintf (stderr,"0 Assigning rmatbeg memory. %d\n", global_m ) ;
p_int = ( int * ) malloc( global_m * sizeof(int));
fprintf (stderr,"1 Assigning rmatbeg memory.\n") ;
if ( p_int == NULL ) {
fprintf (stderr,
"Could not allocate memory for
a_polytope.rmatbeg[%d].\n",global_m);
exit(-1);
};
fprintf (stderr,"2 Assigning rmatbeg memory.\n") ;
//int *a_polytope.rmatbeg decalred earlier as global
aa_polytope.rmatbeg = p_int ;
My output shows "Segmentation fault" when size_for_n = 10
:
Allocating memory for c_buf[10]
Trying to re-allocating memory for c_buf[20]!
Trying to re-allocating memory for c_buf[40]!
Trying to re-allocating memory for c_buf[80]!
Finalizing in re-allocating memory for c_buf[50]!
Assigning memory.
0 Assigning rmatbeg memory. 9000
Segmentation fault
My output is ok when size_for_n = 60
:
Allocating memory for c_buf[60]
Finalizing in re-allocating memory for c_buf[50]!
Assigning memory.
0 Assigning rmatbeg memory. 9000
1 Assigning rmatbeg memory.
2 Assigning rmatbeg memory.
Thanks!