所以我在终端上使用MinGW编译了这段代码,它最初是在Visual Studio中编译的,并没有显示任何错误的迹象。 它是动态数组的代码,在VS中经过几个小时的调试后发现,当我在另一个结构和数组中进行malloc时,复制所有整数,然后将旧数组指向新数组,它不会保留在内存中。此外,大小和阈值不是指针,但它们不应该像结构一样从内存中释放出来吗?代码如下。我也可以在我的GitHub here
中找到它(有点改动)我可能正在做一些非常愚蠢的事情,但我已经把我的想法烧成了这个并且无法得出任何结论。我拒绝在stackoverflow上询问它(因为我的大多数错误都非常愚蠢)但经过几个小时的调试我放弃了。
#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;
}