Realloc包含指向另一个Sruct的指针的结构(分段错误)
我有两个这样的结构:Realloc包含指向另一个Sruct的指针的结构(分段错误),c,pointers,struct,realloc,C,Pointers,Struct,Realloc,我有两个这样的结构: typedef struct Student { char name[80]; char sclass[4]; int phone; } Student; typedef struct Cell { Student* p_student; // pointer to struct bool occupied; // if the cell has been occupied for collisions after delete }
typedef struct Student {
char name[80];
char sclass[4];
int phone;
} Student;
typedef struct Cell {
Student* p_student; // pointer to struct
bool occupied; // if the cell has been occupied for collisions after delete
} Cell;
以及最初使用malloc分配的两个阵列:
Cell *arr_name = malloc(sizeof(Cell) * size),
*arr_phone = malloc(sizeof(Cell) * size);
问题是,当我尝试使用Realloc时,我得到了分段错误:
void insert(int *size, int *numberOfStudents, Cell **arr_name, Cell **arr_phone, char name[80], char sclass[4], int phone) {
// some stuff happening
if(*numberOfStudents > (*size / 1.5)) {
*size = *numberOfStudents * 1.5;
int new_size = sizeof(Cell) * (*size);
Cell *p_name = realloc(*arr_name, new_size); // <-- ERROR HERE
Cell *p_phone = realloc(*arr_phone, new_size);
if(p_name && p_phone) {
*arr_name = p_name;
*arr_phone = p_phone;
}
else printf("Couldn't allocate more memory");
}
void insert(int*size,int*numberofstudent,Cell**arr\u name,Cell**arr\u phone,char name[80],char sclass[4],int phone){
//发生了什么事
如果(*学生人数>(*尺寸/1.5)){
*人数=*学生人数*1.5;
int new_size=sizeof(单元格)*(*大小);
Cell*p_name=realloc(*arr_name,new_size);//问题已解决
感谢@StoryTeller建议使用valgrind调试内存错误。内存被程序中的其他东西弄乱了。@StoryTeller啊,我错过了这一部分。命名东西……:)Paul,请创建一个示例来演示这个问题。问题必须包含足够的代码来重现问题,但不要太多不能直接复制粘贴并自己检查。@StoryTeller我尝试过,但无法在测试环境中重现错误,但如果您感兴趣,我可以以私人消息的形式将整个项目发送给您。谢谢您的回答:)如果您无法重现问题,则意味着您需要进一步调试程序。请重试先从valgrind开始。忘记我之前的消息,我使用了错误的命令。我有很多“大小无效写入…”错误。我猜它就是从那里来的。