0

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;
        }
    }
}
  • 4
    One issue is that you have not allocated memory for `struct LINE *line;`. Hence the `memset` in `split()` will most likely already write to invalid memory, causing the `SIGSEGV`. See also https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault – Andreas Fester Dec 03 '20 at 11:30
  • 4
    `struct LINE *line` is pointer you are trying to write into it without memory allocation – IrAM Dec 03 '20 at 11:30
  • problem solved. Thank you. – Assefa Seyoum Dec 03 '20 at 11:55

0 Answers0