每次运行时,都会在 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 这样的程序的这个问题。
猜测(因为您没有包含 for 的代码GetObjectCount
)您的主Render
循环也有这个问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句