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.