C:使用 Free() 出现段错误

标签 c

我有一个指向结构的指针数组,一旦不再需要它们,我将尝试使用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)

有人可以给我关于这个的提示吗?

最佳答案

在 valgrind 下运行你的程序,大多数时候你不会崩溃,因为你运行在 valgrind 创建的内存空间内,可以说这对你的程序更宽容。

除非尝试释放非指针类型,否则通常不会在释放时出现编译错误。但它会在执行时崩溃,因为您将尝试释放错误的地址。

我非常有兴趣看到您负责释放这些资源的功能,即完整的资源。

您是否在任何地方跟踪数组的大小? 将 array[i] 设置为 NULL 以表示它已被释放并且不再可用?

当指针不可用时,始终将它们设置为 NULL。

关于C:使用 Free() 出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40061699/

相关文章:

c - 通过标准输入发送 SIGINT

c - gcc 函数属性会影响函数指针吗?

c - 编译时对所有 'sem' 和 'pthread' 函数的 undefined reference

c - 如何创建一个代表c数组的 `ffi_type`?

c - Codeblocks、glade、gtk 中的断言失败

c - C 中的无缝内存映射文件

c - 未经许可更改内存值

c - fscanf C - 确定字母而不是数字

c - 将 C 字符串传递给 linux 命令行

c - MIPS 汇编到 C