我有一个指向结构的指针数组,我试图在不再需要它时使用free()
。以下是这些结构的设置方式:
typedef struct {
SDL_Surface *sprite;
SDL_Rect rect;
} Laser;
Laser *fireLaser(char *sprite, int x, int y)
{
Laser *laser = malloc(sizeof(Laser));
laser->sprite = loadSurface(sprite);
laser->rect.x = x;
laser->rect.y = y;
return laser;
}
game->playerLasers[player->laserCount++] = fireLaser("images/laser.bmp", (player->rect.x, player->rect.y);
一旦不再需要,我会尝试使用free()
。
SDL_FreeSurface(game->playerLasers[i]->sprite);
free(game->playerLasers[i]);
我用free(game->playerLasers[i]);
编译它并且没有警告或错误。该程序运行,但只要free()
运行,我就会出现分段错误。
当我使用valgrind
运行程序时,奇怪的是我没有得到分段错误,但是在运行free()
后我确实得到了以下输出:
==2010== Invalid read of size 8
==2010== at 0x4012D8: spawnGrunts (main.c:196)
==2010== by 0x4013FC: updates (main.c:219)
==2010== by 0x4016CD: main (main.c:277)
==2010== Address 0xcfce9c0 is 0 bytes inside a block of size 32 free'd
==2010== at 0x4C2AD90: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2010== by 0x4012FF: spawnGrunts (main.c:197)
==2010== by 0x4013FC: updates (main.c:219)
==2010== by 0x4016CD: main (main.c:277)
==2010== Block was alloc'd at
==2010== at 0x4C29BBE: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2010== by 0x400E65: loadGrunt (main.c:105)
==2010== by 0x4011FE: spawnGrunts (main.c:182)
==2010== by 0x4013FC: updates (main.c:219)
==2010== by 0x4016CD: main (main.c:277)
==2010==
==2010== Invalid free() / delete / delete[] / realloc()
==2010== at 0x4C2AD90: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2010== by 0x4012FF: spawnGrunts (main.c:197)
==2010== by 0x4013FC: updates (main.c:219)
==2010== by 0x4016CD: main (main.c:277)
==2010== Address 0xcfce9c0 is 0 bytes inside a block of size 32 free'd
==2010== at 0x4C2AD90: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2010== by 0x4012FF: spawnGrunts (main.c:197)
==2010== by 0x4013FC: updates (main.c:219)
==2010== by 0x4016CD: main (main.c:277)
==2010== Block was alloc'd at
==2010== at 0x4C29BBE: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2010== by 0x400E65: loadGrunt (main.c:105)
==2010== by 0x4011FE: spawnGrunts (main.c:182)
==2010== by 0x4013FC: updates (main.c:219)
==2010== by 0x4016CD: main (main.c:277)
有人能给我一个暗示吗?
答案 0 :(得分:0)
在valgrind下运行你的程序,你大部分时间都不会崩溃,因为你在valgrind创建的内存区域内运行,这对你的程序来说更宽容了。
除非尝试释放非指针类型,否则通常不会在free上出现编译错误。但它会在执行时崩溃,因为你会试图释放一个糟糕的地址。
我非常有兴趣看到你的职能部门负责释放权利资源,完整的资源。
您是否在任何地方跟踪阵列的大小? 将array [i]设置为NULL以表示它已被释放且不再可用?
当指针无效时,请始终将指针设置为NULL。