简体   繁体   English

Printf 给出分段错误,除非我先执行“printf” - C

[英]Printf gives segmentation fault unless I do a "printf" first - C

I'm trying to import data from a file but I made a mistake ( after this code below) so I was going to make some debugging, adding so the 15th line of this code:我试图从文件中导入数据,但我犯了一个错误(下面这段代码之后)所以我打算进行一些调试,在这段代码的第 15 行添加:

fscanf(input, "%d %d", & numofusers, & numofmovies);
//-----users list allocation
for (int i = 0; i < numofusers; i++) {
    curruser -> usercode = i + 1;

    //without this 7th line I get a segmentation fault at line 15 (without line 15 program termines successfully)
    printf("%d %d %d\n\n", numofusers, numofmovies, curruser -> usercode);
    //through this line of code I understood that it does what I want it to do

    curruser -> next = calloc(1, sizeof(struct user * ));
    curruser = curruser -> next;
}
curruser = headuser;
//--------
printf("!%d!\n", numofmovies);

The first line of the file contains two integers, which are read with no issues, then I try to allocate some memory for the users.该文件的第一行包含两个整数,读取没有问题,然后我尝试为用户分配一些 memory。 If the first printf is there, no segmentation fault and everything works;如果第一个printf存在,则没有分段错误并且一切正常; otherwise it doesn't.否则它不会。 I've already tried some potential solutions from this website but they didn't fix the issue.我已经从该网站尝试了一些可能的解决方案,但他们没有解决问题。 There must be somewhere I'm not aware of...一定有我不知道的地方......

You're allocating the wrong amount of memory:您分配了错误数量的 memory:

calloc(1, sizeof(struct user * ));

You are allocating enough memory for a pointer, not a whole object.您为指针分配了足够的 memory,而不是整个 object。

It should be它应该是

calloc(1, sizeof(struct user));

(And, there's no reason to use calloc here over malloc .) (而且,没有理由在malloc上使用calloc 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM