【发布时间】:2014-02-21 23:17:49
【问题描述】:
我有一个程序,从键盘获取信息并将它们放入一个结构体中,然后将结构体写入一个文件。
但是,当我第二次重新分配内存时,它似乎无缘无故地失败了。此外,如果我输入超过 1 个人的信息,程序最终会因 seg 错误而失败。如果我只输入 1 个人的信息,程序运行良好。
谢谢。
// Program
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
typedef struct person person;
struct person {
char fname[20];
char lname[20];
int num;
};
int main(void){
int size = 0;
int count = 0;
person* listofperson = NULL;
char answer = 'n';
FILE* myfile;
do{
char* buf = (char*)malloc(sizeof(char)*50);
printf("Please enter the person's first name: \n");
fgets(buf, 50, stdin);
if(count == size){
size += 2;
listofperson = (person*)realloc(listofperson, (size_t)(sizeof(person)*size));
}
strncpy((listofperson+count)->fname, buf, 50);
printf("Please enter the person's last name: \n");
fgets(buf, 50, stdin);
strncpy((listofperson+count)->lname, buf, 50);
printf("Please enter the person's number: \n");
fgets(buf, 50, stdin);
sscanf(buf, "%d", &((listofperson+count)->num));
free(buf);
count++;
printf("Do you want to enter another one?\n");
answer = getchar();
getchar();
}while(tolower(answer) != 'n');
myfile = fopen("myfile", "a");
for(int i = 0; i < count; i++){
fprintf(myfile, "%s", (listofperson+i)->fname );
fprintf(myfile, "%s", (listofperson+i)->lname );
fprintf(myfile, "%d\n", (listofperson+i)->num );
}
fclose(myfile);
myfile = NULL;
free(listofperson);
}
【问题讨论】:
-
strncpy((listofperson+count)->lname, buf, 50);但你的数组大小是20。 -
如果没有先在传递给它的指针上调用
malloc(),就不能调用realloc()。 -
如果你将一个空指针传递给 realloc,它就像 malloc 一样工作。见here。
标签: c segmentation-fault realloc