gpt4 book ai didi

c - 访问/释放动态分配的结构数组时出现不需要的行为

转载 作者:行者123 更新时间:2023-11-30 16:46:55 25 4
gpt4 key购买 nike

每次运行时,GDB 都会输出段错误。我正在尝试创建一个动态结构数组。访问/释放数组内的任何内容时出现错误。

结构:

typedef struct{
SDL_Texture* texture;
SDL_Rect textureSelect;
SDL_Rect objectCollision;//this doesnt have the accuracy of floats, so that might take more work than I want. Use this to get world coordinates
SDL_Rect objectTransform;
float objectVelX;
float objectVelY;
float objectX;
float objectY;
float objectRotation;
unsigned short hasCollision;
unsigned short hasPhysics;
unsigned short used;
unsigned short visible;
}Object;

罪魁祸首之一:

unsigned short firstCalled = 0;
Object *objects = NULL;
unsigned long objectAmmount = 0;

unsigned long AddObject(SDL_Rect collisionRect, SDL_Rect selectTexture, const char *textureUrl){

if(firstCalled){//for first time calling

objects = (Object *)malloc(sizeof(Object));//this is fine

if(objects == NULL){

printf("Critical memory allocation error\n");

} else{
printf("Allocated memory\n");
}

} else{

Object *tempObjects = (Object *)realloc(objects, (objectAmmount + 2) * sizeof(Object));//have to do 1+ to make room for more

if(tempObjects == NULL){

printf("CRITICAL*** Out of memory/memory error\n");

} else{

printf("Reallocation successfull\n");

objects = tempObjects;
tempObjects = NULL;

}
}
//Which then goes on to set each variable to a wanted default value

objects[objectAmmount].textureSelect = selectTexture;
objects[objectAmmount].objectCollision = collisionRect;
objects[objectAmmount].objectTransform.x = 0;
//...

objectAmmount++;



if(firstCalled){//for first time calling
//just give the function that called this this number because this is the object ID;
firstCalled = 1;
return objectAmmount - 1;
} else{
return objectAmmount;
}
}

在渲染函数中:

Object *tempAccessObject = NULL;
void Render(){
for(i = 0; i <= GetObjectCount(); i++){
tempAccessObject = GetObject(i);//GetObject returns a pointer to the specific point in the array
//use the variables in the array to render the objects
}
}

最后是销毁函数:

void DestroyScene(){
firstCalled = 0;
if(objects != NULL){
printf("Nothing to free\n");
unsigned long i;
for(i = 0; i <= objectAmmount; i++){
if(objects[i].texture != NULL){
SDL_DestroyTexture(objects[i].texture);
}
}
free(objects);
objects = NULL;
}

objectAmmount = 0;
}

最佳答案

看起来像是索引问题。以这个循环为例:

for(i = 0; i <= objectAmmount; i++){
if(objects[i].texture != NULL){
SDL_DestroyTexture(objects[i].texture);
}
}

该条件表达式应该是 i < objectAmmount因为您不想访问 objects[objectAmmount]因为它将未初始化或超出您分配的内存范围,具体取决于您调用 AddObject 的次数。您malloc只有 1 个元素,但是 realloc每次额外增加 2,这可以掩盖像 valgrind 这样的程序的这个问题。

猜测(因为您没有包含 GetObjectCount 的代码)您的主要 Render Loop也有这个问题。

关于c - 访问/释放动态分配的结构数组时出现不需要的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43545773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com