0

我在 C 中使用 getline() 函数,当我多次使用它时,它一直给我段错误,就像在数组中一样。这是我写它的方式:

temp = (char *)malloc(sizeof(char)*clen); 
read = getline(&temp, &clen, stdin);
tn = strtok(temp, ",");
strcpy(travel[tripnum].name, tn);
tn = strtok(NULL, ",");
travel[tripnum].country = tn;
free((void *) temp);

如果我声明不正确,请告诉我

4

4 回答 4

2

As seen in this getline tutorial you need to allocate (clen + 1). One extra for the terminal NULL.

于 2011-03-29T07:40:00.580 回答
0

尝试将其与其他人所说的一起使用。我觉得在 getline 函数中 clen 应该在没有 & 符号的情况下使用。像 read = getline(&temp, clen, stdin);

于 2011-03-29T09:17:20.327 回答
0

Did you try doing this temp = (char *)malloc(sizeof(char)*clen+1);

Because of a null terminated string

于 2011-03-29T07:46:11.773 回答
0

您的tn变量(的结果strtok())指向temp缓冲区内。

temp缓冲区在代码段的最后一行被销毁,但是其中一个指针tn(指向内部temp)已保存在travel[tripnum].country.

travel[tripnum].country是一个悬空指针,通过它的所有访问都是无效的。

于 2011-03-29T09:29:34.020 回答