Question

When I try to execute this program I am getting segmentation fault. What could be the reason?

    #include<stdio.h>
    #include<malloc.h>
    #include<string.h>

    #define UWT unsigned int 
    #define DIR_LEN 1024
    typedef struct fileParsedData{
            UWT weight;
            char *dir;
    }FILEPARSEDATA;

    int parseData(char *fileData,FILEPARSEDATA *fPD){

            char tmpStr[DIR_LEN] = {0};

            strcpy(tmpStr,strchr(fileData,' ') + 1);
            *(strchr(tmpStr,'\n')) = '\0';
            fPD->weight = atoi(fileData);

            if((fPD->dir = (char *)malloc(strlen(tmpStr) + 1)) != NULL ){
                    memset(&fPD->dir,0,strlen(tmpStr)+1);
                    strcpy(fPD->dir,tmpStr);
                    return 0;
            }
            return -1;
    }

    int main(){
            char fileData[10] = " hai\n";
            FILEPARSEDATA fPD;
            memset(&fPD,0,sizeof(FILEPARSEDATA));
            parseData(fileData,&fPD);
            return 0;
    }
Was it helpful?

Solution

The problem is here:

memset(&fPD->dir,0,strlen(tmpStr)+1);

The above line should read:

memset(fPD->dir,0,strlen(tmpStr)+1);

Otherwise, you're not only zeroing out the fPD->dir pointer, you're also corrupting memory immediately after it. Once you've zeroed out the pointer, the subsequent strcpy() into the pointed-to memory segfaults.

In fact, that entire memset() line appears redundant since it's followed immediately by the strcpy().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top