我有两个结构的数组。一个在二进制搜索树里面。
typedef struct Equipo {
char nombre[50];
char marcaMoto[30];
int puntuaciones;
struct Piloto pilotos[18];
int pilotoLibre;
struct nodo* izquierdo;
struct nodo* derecho;
} Equipo;
typedef Equipo Arbol;
typedef struct Piloto {
int dorsal;
char inicialNombre[1];
char apellido1[50];
char nacionalidad[3];
int puntuacion;
struct Premio* premios[18];
int premioLibre;
} Piloto;
void InsertarPilotoEquipo(Equipo* arbol, char nombre[], Piloto* p) {
if (!arbol) {
return 0;
}
Equipo* equipo = ObtenerEquipo(arbol, nombre);
if (equipo) {
struct Piloto* pilotos[18];
pilotos[equipo->pilotoLibre] = p;
equipo->pilotoLibre++;
equipo->puntuaciones += p->puntuacion;
memcpy(equipo->pilotos, p, sizeof equipo->pilotos);
return 1;
} else {
return 0;
}
}
还有一个在链接列表里面
typedef struct Premio {
char nombre[50];
int puntos;
} Premio;
int insertarGP(Piloto* piloto, char nombre[50], int puntos) {
struct Premio* p = (Premio *) malloc(sizeof(Premio *));
strncpy(p->nombre, nombre, 50);
p->puntos = puntos;
struct Premio* premios[18];
premios[piloto->premioLibre] = p;
piloto->premioLibre++;
piloto->puntuacion += puntos;
memcpy(piloto->premios, p, sizeof piloto->premios);
return 1;
}
其实操作是一样的,但功能是一样的 InsertarPilotoEquipo
行而不灵 insertarGP
没有。如果我调试,我得到的是行 strncpy(p->nombre, nombre, 50);
的错误。
output: malloc.c:2379: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
make: *** [makefile:9: compile] Abortado (core dumped) [Núcleo vaciado a un archivo]
在函数的其余部分,我得到:
malloc(): corrupted top size
make: *** [makefile:9: compile] Abortado (core dumped) [Núcleo vaciado a un archivo]
为什么会出现这种情况 你有什么解决办法吗?
在MALLOC中更新没有CASTING。
int insertarGP(Piloto* piloto, char nombre[50], int puntos) {
struct Premio* p = malloc(sizeof(*p));
strncpy(p->nombre, nombre, 50);
p->puntos = puntos;
struct Premio* premios[18];
premios[piloto->premioLibre] = p;
piloto->premioLibre++;
piloto->puntuacion += puntos;
memcpy(piloto->premios, p, sizeof piloto->premios);
return 1;
}
这一行在 insertarGP
struct Premio* p = (Premio *) malloc(sizeof(Premio *));
是坏的,因为只分配了一个指针的缓冲区,而且在典型的环境中,它被用于大于一个指针大小的结构。
这一行应该是
struct Premio* p = malloc(sizeof(Premio));
或
struct Premio* p = malloc(sizeof(*p));