I want to split the string pointed by buf, and store each comma separated values in the LINE struct. However, it produces segmentation fault. To my knowledge, I am not writing to a read-only memory (eg. if I try to modify buf). I don't know what the cause for the segmentation fault is. My code is given below.
#include <stdio.h>
#include <string.h>
#define NAMELENGTH 15
enum LINE_ATTR{
FIRST_NAME,
LAST_NAME,
IP,
PORT,
DATA
};
struct LINE{
char first_name[NAMELENGTH];
char last_name[NAMELENGTH];
char IP[50];
char port[50];
char data[1024];
};
void split(char *buf, struct LINE* line);
int main()
{
struct LINE *line;
char *buf = "new user,user,127.0.0.1,47528,";
split(buf, line);
return 0;
}
void split(char *buf, struct LINE* line){
enum LINE_ATTR attr = FIRST_NAME;
int j = 0;
memset(line, '\0', sizeof(struct LINE));
for (int i = 0; i < strlen(buf); i++){
switch(attr){
case FIRST_NAME:
if (buf[i] == ','){
attr++;
j = 0;
} else {
line->first_name[j] = buf[i];
j++;
}
break;
case LAST_NAME:
if (buf[i] == ','){
attr++;
j = 0;
} else{
line->last_name[j] = buf[i];
j++;
}
break;
case IP:
if (buf[i] == ','){
attr++;
j = 0;
} else {
line->IP[j] = buf[i];
j++;
}
break;
case PORT:
if (buf[i] == ','){
attr++;
j = 0;
} else {
line->port[j] = buf[i];
j++;
}
break;
case DATA:
if (buf[i] == ','){
attr++;
j = 0;
} else {
line->data[j] = buf[i];
j++;
}
break;
}
}
}