Here's a question for you pros:
I am making a array ADT type that dynamically resizes itself when you attempt to access elements that would normally be out-of-bounds. I have initialized the struct to size 0 and allocated enough memory for 16 integers in another function that I have already debugged and called.
array.c
Code:
struct arrayADT
{
unsigned int size;
unsigned int capacity;
int *data;
};
void ArrayADT_setElement(struct ArrayADT *array, const unsigned index, const int newValue)
{
struct arrayADT *p = (struct arrayADT *)array;
if (index >= p->size)
{
ArrayADT_resize(array, index);
}
p->data[index] = newValue;
}
void ArrayADT_resize(struct ArrayADT *array, const unsigned newsize)
{
struct arrayADT *p = (struct arrayADT *)array;
if (newsize <= 16)
{
p->capacity = 16;
}
else if (newsize < p->capacity)
{
while ((p->capacity >> 1) >= newsize)
{
p->capacity = p->capacity >> 1; // divide by 2
}
}
else
{
while (p->capacity < newsize)
{
p->capacity = p->capacity << 1; // mult by 2
}
}
p->size = newsize + 1;
if (!realloc(p->data, sizeof(int) * p->capacity))
{
printf("Memory allocation error.\n");
exit(1);
}
}
I am having a very strange memory problem. I have spent all morning running this program through the debugger and have narrowed the problem down to this line
p->data[index] = newValue;
which causes an memory access violation exception. Also if I create a large sized array, say 4000 ints, when I try to free the memory I get a possible heap corruption exception...
In Linux I don't get a exception but my array size and capacity become junk values.
Any help is appreciated I am stuck here...