I am trying to create a Dynamic Integer Array in C which should automatically double its size once full.
To extend the size of the Array I want to use the realloc function. Unfortunately there seems to be some problem with the pointer to the data of my DynamicArray and GCC crashes :( Does anyone have a clue why? If I realloc just after using malloc, there is no crash. I have checked the pointer address and it is not changed between malloc and realloc.
The following are my header file declarations for the struct:
struct DynamicArray
{
unsigned int size;
unsigned int capacity;
int *data;
}; // ----- end of struct DynamicArray -----
typedef struct DynamicArray DynamicArray;
// ##### EXPORTED FUNCTION DECLARATIONS
DynamicArray* dn_new ( unsigned int capacity );
int dn_append ( DynamicArray *a, int elem );
This is my main class used for testing:
int
main ( int argc, char *argv[] )
{
DynamicArray *a1;
int i;
a1 = dn_new ( 5 );
// here six integers are inserted, the sixth causes the realloc crash as this is where I want to extend
dn_append ( a1, 5 );
dn_append ( a1, 7 );
dn_append ( a1, 8 );
dn_append ( a1, 11 );
dn_append ( a1, 13 );
dn_append ( a1, 15 );
return 0;
} // ----- end of function main -----
These are the functions dn_append and dn_new which are called by the main:
DynamicArray*
dn_new ( unsigned int capacity )
{
struct DynamicArray *a = malloc(sizeof(struct DynamicArray));
a->data = (int *)calloc(capacity,capacity * sizeof(int));
printf("allocated %d\n",a->data);
a->size=0;
a->capacity=capacity;
printf("array created\n");
if (a == NULL){
return NULL;
}
else{
return a;
}
}
int
dn_append ( DynamicArray *a, int elem )
{
short extended = 0;
if (a->size==a->capacity){
a->capacity=a->capacity*2;
printf("allocated %d\n",a->data);
//here is exactly where the error occurs
a->data = (int *)realloc(a->data,a->capacity * sizeof(int));
printf("array extended to have capacity for %d integers\n",a->capacity);
extended=1;
}
a->data[(a->size-1)] = elem;
a->size++;
printf("element %d appended to array\n",elem);
return extended;
}