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;
}
The problem is here:
The above line should read:
Otherwise, you’re not only zeroing out the
fPD->dirpointer, you’re also corrupting memory immediately after it. Once you’ve zeroed out the pointer, the subsequentstrcpy()into the pointed-to memory segfaults.In fact, that entire
memset()line appears redundant since it’s followed immediately by thestrcpy().