1

I currently have a struct for storing port and destination address info which I want to populate with data read from a simple text file.

typedef struct {
    int listen_port;
    int forward_port;
    char *forward_addr;
} Route;

If I just assign 30 it works fine.

E.G.

while((read = getline(&line, &length, f)) != -1) {
    Route *srv = (Route*) malloc(sizeof(Route));
    srv->listen_port = 30;  //works fine
    /* rest of code */
}

But if I try to use strtok to tokenize a line read from file 80,127.0.0.1,8080 and then assigned that to the srv->listen_port, I get a seg fault.

E.G.

while((read = getline(&line, &length, f)) != -1) {
    int port = atoi(strtok(line, ","));
    Route *srv = (Route*) malloc(sizeof(Route));
    srv->listen_port = port;  //seg fault
    /* unreachable code */
}

Can someone explain why this is happening? I'm stumped as to why it isn't working.

Thanks in advance.

user1231232141214124
  • 1,339
  • 3
  • 16
  • 22

1 Answers1

3

See

atoi — how to identify the difference between zero and error?

Also, strtok can just return NULL if line is a zero length string, so there is potentially atoi(NULL)

This code's behavior can be so undefined...

1) intialize line to NULL, getline will allocate space for you ( if it is not NULL, it will assume you already allocated it )

2) free line after use

3) use strtol or scanf to get the integer, since you and the compiler can't be sure the input line will contain a number in ascii digits

4) check the return value of malloc , it returns NULL in case of failure

As a general rule, treat every possible error case, it is a necessary best practice in C

Community
  • 1
  • 1
Gábor Buella
  • 1,840
  • 14
  • 22
  • Yeah my C is extremely rusty. `atoi` wasn't liking the `strtok` from the `getline`. But once I changed it from `char* line` to `char line[BUFFER]` in combination with `fgets`, everything worked like a charm. I appreciate the help. – user1231232141214124 Mar 20 '14 at 21:57