[英]I need to know if I am using getline correctly
I am using the getline() function in C and it keeps giving me seg faults when I use it more that once, as in for an array. 我在C中使用了getline()函数,当我多次使用它时,它一直给出我的seg错误,就像数组一样。 Here is how I've written it:
这是我写的方式:
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);
Please let me know if I am declaring something incorrectly 如果我声明错误,请告诉我
As seen in this getline tutorial you need to allocate (clen + 1). 如此getline教程中所示,您需要分配(clen + 1)。 One extra for the terminal NULL.
一个额外的终端NULL。
Did you try doing this temp = (char *)malloc(sizeof(char)*clen+1); 你尝试过这个temp =(char *)malloc(sizeof(char)* clen + 1);
Because of a null terminated string 由于空终止字符串
Try using this along with what others have told. 尝试使用此以及其他人所说的内容。 I feel in getline function clen should be used without the ampersand.
我觉得getline函数clen应该在没有&符号的情况下使用。 Like read = getline(&temp, clen, stdin);
像read = getline(&temp,clen,stdin);
Your tn
variable (result of strtok()
) points inside the temp
buffer. 你的
tn
变量( strtok()
结果)指向temp
缓冲区。
The temp
buffer is destroyed in the last line of your snippet, however one of the tn
pointers (to the inside of temp
) has been saved in travel[tripnum].country
. temp
缓冲区在代码段的最后一行被销毁,但是其中一个tn
指针(到temp
的内部)已保存在travel[tripnum].country
。
This travel[tripnum].country
is a dangling pointer and all accesses through it are invalid. 这个
travel[tripnum].country
是一个悬空指针,通过它的所有访问都是无效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.