开发者

I need to know if I am using getline correctly

I am using the getline() function in C and it keeps giving me seg fa开发者_如何学JAVAults when I use it more that once, as in for an array. 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). One extra for the terminal NULL.


Did you try doing this 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. Like read = getline(&temp, clen, stdin);


Your tn variable (result of strtok()) points inside the temp buffer.

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.

This travel[tripnum].country is a dangling pointer and all accesses through it are invalid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜