随机内存访问冲突

时间:2016-08-31 14:25:24

标签: c memory

我有这个示例代码:

map *d;

i = MAP_SIZE;
j = sizeof(map);
d = malloc(MAP_SIZE);

if (d == NULL) {
    exit(EXIT_FAILURE);
}

dest.x = dest.y = 0;

for (i = 0; i < WINDOW_HEIGHT / AREA_RESOLUTION; i++)
{
    for (j = 0; j < WINDOW_WIDTH / AREA_RESOLUTION; j++)
    {
        k = GetAreaPos(j, i);
        Area = d[k];
        dest.x = j*AREA_RESOLUTION;
        dest.y = i*AREA_RESOLUTION;
        if (Area->landType == DESTRUCTIBLE_BRICK) {      //GOT ERROR HERE
            SDL_QueryTexture(Game_Texture->Explodable, NULL, NULL, &dest.w, &dest.h);
            SDL_RenderCopy(Renderer, Game_Texture->Explodable, NULL, &dest);
        }
        if (Area->landType == INDESTRUCTIBLE_BRICK) {
            SDL_QueryTexture(Game_Texture->Solidblock, NULL, NULL, &dest.w, &dest.h);
            SDL_RenderCopy(Renderer, Game_Texture->Solidblock, NULL, &dest);
        }
    }
}
free(d);
  

MAP_SIZE = sizeof(地图)

我使用Visual Studio,当我运行没有断点的调试时,我总是在第一个循环中出现内存访问冲突。

有断点和缓慢/恒定的F5推,没有错误,循环芬兰也是......

我不明白为什么会出现这个错误,在这个例子中2个循环没有100个回合,违规是完全随机的,有时在第5个回合,有时是在第90个...

此代码示例在另一个外部循环中运行,当第一次执行正常时,其他代码从不会出现任何违规错误。

更新1

现在,我也使用我的d变量并退出if malloc() return NULLGetAreaPos()返回正确的值,但内存违规总是在第二个和第六个转弯的第二个FOR循环中随机地在第一个if条件上进行测试

标题定义:

#define MAP_SIZE sizeof(map)
#define AREA_SIZE sizeof(union area)
#define AREA_RESOLUTION 64
#define MAP_WIDTH 10//28
#define MAP_HEIGHT 10//14

//#pragma pack(1)
typedef enum {
    EMPTY = 00,
    INDESTRUCTIBLE_BRICK = 10,
    DESTRUCTIBLE_BRICK = 11
} landType;

typedef enum {
    BONUS_BOMB_SCOPE = 000,
    MALUS_BOMB_SCOPE = 001,
    BONUS_BOMB_AMOUNT = 010,
    MALUS_BOMB_AMOUNT = 011,
    BONUS_PLAYER_SPEED = 100,
    MALUS_PLAYER_SPEED = 101,
    NO_BONUS_MALUS = 110,
    NO_MALUS_BONUS = 111,
} bonusType;

union area {
    struct {
        bool inFire :4;
        landType landType :8;
        bool presenceBomb :4;
        bool presenceBonus :4;
        bonusType typeBonus :12;
    };
    char c;
};
//#pragma pack(0)

typedef union area map[MAP_WIDTH * MAP_HEIGHT];

1 个答案:

答案 0 :(得分:0)

首先声明指针map *d;并为其分配内存d = malloc(MAP_SIZE);但忽略返回值......

if (d == NULL)表示malloc无效,而(Area->landType == DESTRUCTIBLE_BRICK)会导致UB [因为Area = Map[k];],但您的代码无法防范,而且可能会崩溃< / p>