I was trying to write a brief example for scarlet00014 ("How do I read this in as a string?") using strtok in a method I've used dozens of times before.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[]) {
short int i=0;
size_t len;
char *line=NULL, *tok, DL[]=":\n";
FILE *fstRO=fopen("/root/test/test.txt", "r");
struct {char *name;
int age;
} *example;
while((getline(&line,&len,fstRO)) != -1) {
tok=strtok(line,DL);
printf("%d: %s=%d\n", i,tok,strlen(tok));
example[i].name=malloc(strlen(tok)+1);
strcpy(example[i].name,tok);
puts(example[i].name);
tok=strtok(NULL,DL);
example[i].age=atoi(tok);
free(line);
i++;
}
}
except now it causes this:
0: Jamie lynn=10
Segmentation fault
which gdb says is caused by example[i].name=malloc(strlen(tok)+1);
As I was saying, the example, as far as I can tell, is EXACTLY like other routines I've already written that work fine.
Where did I get confused?