我有两个结构数组。二叉搜索树中的一个:
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中进行铸造的更新
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;
}
但是程序仍然在memcpy(piloto->premios, p, sizeof piloto->premios);
行中,出现相同的错误:
malloc(): corrupted top size
make: *** [makefile:9: compile] Abortado (core dumped) [Núcleo vaciado a un archivo]
[C0中的这一行
insertarGP
不好,因为只分配了一个指针的缓冲区,并且它用于在典型环境中大于一个指针大小的结构。
该行应该是
struct Premio* p = (Premio *) malloc(sizeof(Premio *));
或
struct Premio* p = malloc(sizeof(Premio));
另请参见: struct Premio* p = malloc(sizeof(*p));