C语言 尝试释放数组时出现访问冲突错误



我目前正在为一个个人项目制作结构。我正在尝试使用动态分配的二维数组,然后释放它们占用的空间。当我尝试释放分配的空间时发生错误。

我能够将问题的根源缩小到我为破坏我的结构而设置的功能,但无法查明其中错误的原因。更令人担忧的是,错误(访问冲突)只触发了一半的时间。 我已经包含了下面的功能,并附有一些评论。如果我在这里包含太多代码,我很抱歉,但我真的迷失在文字上,并且确实觉得我初始化结构的方式可能会影响我是否正确销毁它们。

#include <stdio.h>
#include <stdlib.h>
typedef struct f_part f_part;
typedef struct field field;
//these are the structures I used:
//part of a field: includes a character and a color
struct f_part
{
char caractere;
short int color;
};

//field: points to a bidimensionnal array of f_part, and remember its size
struct field
{
int fsize_x;
int fsize_y;
f_part **fbody;
};
field* fieldInitialize(const int size_x, const int size_y)  //this function seems to work correctly, I've mostly added it as an indicator
{
field* terrain = malloc(sizeof(*terrain));
if (terrain == NULL)
printf("fail1");
terrain->fsize_x = size_x;
terrain->fsize_y = size_y;
f_part* ptrToFPart = NULL;
terrain->fbody = malloc(sizeof(ptrToFPart) * size_x);   //this is where I allocate the space for an array of pointers
if (terrain->fbody == NULL)
printf("fail2");
int i,j;
for (i = 0 ; i < size_x ; i++)
{
terrain->fbody[i] = malloc(sizeof(f_part) * size_y);
for (j = 0 ; j < size_y ; j++)
{
terrain->fbody[i][j].caractere = 'a';
terrain->fbody[i][j].color = 0;
}
}
terrain->fsize_x = size_x;
terrain->fsize_y = size_y;
return terrain;
}

void fieldDestroy(field* terrain)   //this is the function that is supposed to destroy the object and free the memory, and fails
{
int i;
for (i = 0 ; i < terrain->fsize_x ; i++)
{
free(terrain->fbody[i]);    //this part always goes well
}
printf("flag 1n");
free(terrain->fbody);   //this is where the access violation happens, when it does
printf("flag 2n");
free(terrain);      //this part goes well too
printf("flag 3n");
}
int main()
{
field* testField = fieldInitialize(5, 5);
fieldDestroy(testField);       //This is the function that fails. Sometimes.
return 0;
}

当我尝试释放为指针数组分配的空间时,错误系统地发生在倒数第二行。除非它并不总是发生!有时,我可以释放地形>身体,一切都很顺利,但有时,我无法释放空间。 我得到的错误是0xC0000005,这显然转化为"访问冲突"。我知道这在处理动态内存分配时很常见,但是为什么我似乎只有一半的时间出现错误?

编辑 :好的,所以我编辑了一些代码。有趣的是,虽然我的 Windows 10 会在标志 1 和标志 2 之间失败,但我的 Windows 7 在标志 2 和 3 之间失败,并且也返回0xC0000005错误。但同样,只是偶尔。

在 C 语言中,结构名称前面必须加上struct。 所以你的函数应该被声明:

struct field* fieldInitialize( ... )

并且您的分配应该是

struct field* terrain = malloc(sizeof(struct field));

您还可以将这些结构定义为类型:

typedef struct
{
int fsize_x;
int fsize_y;
struct f_part **fbody;
} field;

最新更新