I need to create a dynamic array which is than populated by a function. I have no way to know in advance how big is that array. So I did the following:
TAB_TYPE *column_types = malloc(100*sizeof(TAB_TYPE));
hExtract = make_table_definition(jsstr, tokens, column_types);
I randomly decided to allocate 100 elements. Inside the function I resized it with:
realloc(column_types, tokens[0].size /2 * sizeof(TAB_TYPE)))
The above line yielded the following error when compiling with GCC:
error: ignoring return value of ‘realloc’, declared with attribute warn_unused_result
Which I managed to by pass like this:
if (!(int *) realloc(column_types, tokens[0].size /2 * sizeof(TAB_TYPE)))
log_die("Failed to allocate memory to column_types!");
log_die
is existing with message to stderr.
I also tried the following approach, which yields segmentation fault:
//first declare a NULL pointer:
TAB_TYPE *column_types = NULL;
//inside the function
TAB_TYPE *t = realloc(column_types, tokens[0].size /2 * sizeof(TAB_TYPE));
if (!t){
log_die("Failed to allocate memory to column_types!");
}else{
column_types = t ;
}
// outside the function
for (int i=0; i < tokens[0].size / 2; i++ )
printf("Type %d : %d\n", i, column_types[i]); -> SEGMENTATION FAULT!!!
My questions are two:
- Is this the way to do it?
- Why does the second approach end with segmentation fault?