Search code examples
csegmentation-faultfile-descriptor

SIGSEGV while reading file using file descriptor


I'm trying to read file using file descriptor. The file descriptor is correct, so, the file is open correctly. The error is given when the program reads the last line

This is the code:

void readFile(char* filePath){
int fd,i=0;
char *c= NULL;
int read=1;
fd = open(filePath, O_RDONLY );
char **config;
config=(char**)malloc(4 * sizeof(char*));

if(fd<0){
    printf("Error");
} else {
    while (read==1){
        c=readLine(fd);

        if(*c=='\0'){
            read=0;
        }else{
            config[i]=(char*) malloc(sizeof(char));
            strcpy(config[i], c);
            i++;
        }
    }
    close(fd);
}

}

char *readLine(int fd){
 char character;
 char *array= malloc(1);
 unsigned int siz=1;


 while (read(fd, &character, 1) > 0 && character!='\n'){
     array=realloc(array, siz + 1);
     array[siz - 1]=character;
     siz ++;
 }
 array[siz - 1]='\0';
 return array;

Solution

  • The program has several flaws, including not freeing dynamically allocated memory (that returned by readline for example).

    However, what is preventing the program to run at least is the lack of space of each of the config[i] locations. You just reserve space for one character malloc(sizeof(char)), but you have to reserve space for the whole string that afterwards is copied, plus the ending '\0': malloc(strlen(c) + 1). Also, take into account that using strlen, strcpy, etc. expects the string to contain non-binary data, and may fail with different encodings, etc.

    Another solution would be to just assign config[i] to the returned c string, and later freeing it when freeing config. You would avoid the copy of the string.