简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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