So I compiled this code both at the terminal with MinGW and it was originally compiled in Visual Studio both not showing any sign of wrong-doing. It is a code for Dynamic Arrays and after hours of debugging in VS I found that when I malloc another structure and array, copy all the integers and then point the old array to the new one it won't remain in the memory. Also the size and threshold are not pointers, but shouldn't they not be freed from memory just like the structure? The code is as follows. I also have it available (a bit changed) at my GitHub here
I'm probably doing something really stupid, but I've burned my mind into this and can't get to any conclusions. I resisted asking it at stackoverflow (because most of my mistakes are really dumb) but after hours of debugging I gave up.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct DArray {
int *array; // Array of integers
int size; // Actual Size
int maxSize; // Maximum size.
bool threshold; // maxSize / 2
} DArray;
DArray * getDArray(int maxSize);
int pushValueDArray(DArray *array, int value);
int popValueDArray(DArray *array);
int displayDArray(DArray *array);
int checkSize(DArray *array);
DArray * getDArray(int maxSize)
{
if (maxSize < 0) {
printf("\nFATAL ERROR\n");
return NULL;
}
DArray *newArr = (DArray *)malloc(sizeof(DArray));
newArr->size = 0;
newArr->maxSize = maxSize;
newArr->threshold = false;
newArr->array = (int *)malloc(sizeof(int) * maxSize);
return newArr;
}
int pushValueDArray(DArray *array, int value)
{
checkSize(array);
array->array[array->size] = value;
(array->size)++;
return 0;
}
int popValueDArray(DArray *array)
{
checkSize(array);
array->array[array->size] = 0;
(array->size)--;
return 0;
}
int displayDArray(DArray *array)
{
int i;
if (array->size == 0) {
printf("\n[ Empty ] \n");
return 1;
}
printf("\n[ ");
for (i = 0; i < array->size; i++) {
printf("%d, ", array->array[i]);
}
printf("nil ]\n");
return 0;
}
int checkSize(DArray *array)
{
int i;
if (array->size > array->maxSize / 2) array->threshold = true;
if (array->size >= array->maxSize - 1) {
// Grow
DArray *nArray = getDArray(array->maxSize * 2);
DArray *kill = array;
for (i = 0; i < array->size; i++) {
nArray->array[i] = array->array[i];
}
nArray->size = array->size;
nArray->threshold = false;
array = nArray;
free(kill);
return 0; // OK
}
else if (array->threshold && array->size < array->maxSize / 2) {
// Shrink
DArray *nArray = getDArray(array->maxSize / 2 + 1);
DArray *kill = array;
for (i = 0; i < array->size; i++) {
nArray->array[i] = array->array[i];
}
nArray->size = array->size;
nArray->threshold = false;
array = nArray;
free(kill);
return 0; // OK
}
else {
// OK
return 0;
}
}
int main(int argc, char const *argv[])
{
DArray *array = getDArray(100);
int i;
for (i = 0; i < 2000; i++) {
pushValueDArray(array, i);
}
for (i = 0; i < 2000; i++) {
popValueDArray(array);
}
displayDArray(array);
printf("\nsize %d", array->size);
return 0;
}