瓦格朗给我
有条件的跳跃或移动取决于未初始化的值和
未初始化的值是通过堆分配创建的
我当前代码中的错误:
void createMonsters(Game *game) {
(void) game;
Creature *nr;
int x = 0;
int r = 0;
int y = 0;
int check = 0;
int c = game->opts.numMonsters;
int nrm=0;
nr=malloc( sizeof (Creature) * c);
for(int i=0;i<c;i++){
game->numMonsters=nrm;
r = rand()%2;
x = rand() % game->opts.mapWidth;
y = rand() % game->opts.mapHeight;
check=1;
while(check!=2){
check = isBlocked(game,x,y);
if(check==1){
x = rand() % game->opts.mapWidth;
y = rand() % game->opts.mapHeight;
}
else{
nr[i].pos.y=y;
nr[i].pos.x=x;
nr[i].attack=attackPunch;
nrm += 1;
check=2;
}
}
if(r==0){
nr[i].name[0] = 'C';
nr[i].maxhp = 15;
nr[i].hp = nr[i].maxhp;
nr[i].sign = 'C';
}
else{
nr[i].name[0] = 'D';
nr[i].maxhp = 50;
nr[i].hp = nr[i].maxhp;
nr[i].sign = 'D';
}
game->monsters=nr;
}
game->numMonsters=nrm;
}
int isBlocked(Game *game, int x, int y)
{
(void) game;
(void) x;
(void) y;
if(x>game->opts.mapWidth || y>game->opts.mapHeight){
return 1;
} }
if(game->numMonsters!=0){
for (unsigned int i = 0; i < game->numMonsters; i++){
Creature *monst = &game->monsters[i];
if (monst->pos.x == x && monst->pos.y == y){
return 1;
}}
}
if(game->map.tile[y][x]==TILE_OPEN || game->map.tile[y][x]==TILE_ROOM){
return 0;
}
else{
return 1;
}
}
Valgrind指向nr = malloc(sizeof(Creature)* c);
所以我做错了什么?
typedef struct creature_st {
char name[20]; // name of the monster
char sign; // character that represents monster on the game display
Point pos; // location of the monster
float hp; // current hitpoints
unsigned int maxhp; // maximum hitpoints
void (*move)(struct game_st *, struct creature_st *); // current movement algorithm for monster
void (*attack)(struct game_st *, struct creature_st *); // current attack algorithm for monster
} Creature;
完整的valgrind错误:
== 386 ==有条件的跳跃或移动取决于未初始化的值== 386 ==在0x4C2C1B8:strlen(在/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)== 386 == x test_createMonsters(test_source.c:179)== 386 == by 0x409377:srunner_run(in / tmc / test / test)== 386 == by 0x4057C9:tmc_run_tests(tmc-check.c:134)== 386 == 0x405464:main(test_source.c:529)== 386 ==通过在0x4C28C20上的堆分配== 386 ==创建了未初始化的值:malloc(在/ usr / lib / valgrind / vgpreload_memcheck-amd64-linuxso。 = 386 ==通过0x4026C2:createMonsters(monster.c:288)== 386 ==通过0x403ADF:test_createMonsters(test_source.c:119)== 386 ==通过0x409377:runner_run =(在/ tmc / test / = 386 ==通过0x4057C9:tmc_run_tests(tmc-check.c:134)== 386 ==通过0x405464:main(test_source.c:529)== 386 ==
typedef struct game_st {
Map map;
unsigned int numMonsters; // number of elements in 'monsters' array
Creature *monsters; // dynamic array of all monsters
Point position; // current position of the player
float hp; // hit points, should never be higher than 'maxhp'
unsigned int maxhp; // maximum hit points
Options opts;
} Game;
最佳答案
未初始化的值已在代码中的某个位置创建,该函数将访问该值。使用--track-origins=yes选项来valgrind跟踪该值的来源。
关于c - Valgrind:有条件的跳跃或移动取决于未初始化的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37104739/