segmentation fault when trying to allocate memory for a string in a struct

Working on a problem where I have to read data from a file into a struct. The file is organized so that there is a name, a few lines of ASCII art terminated by a # and a rating. Here is an example Sample Name ( S ) ( S ) # 5 I have my struct set up like this: typedef struct { char* name; char* art; int rating; }CASE; My problem is that I keep getting a `segmentation fault` when I try to dynamically allocate memory for the name string in the code below: /*FPin is file pointer to the txt file and all is the array of structs*/ void readFile(FILE* FPin, CASE** all) { CASE* walker = *all; int count = 0; char buffer[160]; char* bufferPtr = buffer; char nameBuffer[100]; /*Reads in the name*/ while(fscanf(FPin, "%[^\n]", nameBuffer)) { printf("string is %s\n", nameBuffer); walker->name = (char*)malloc(sizeof(char)*(strlen(nameBuffer+1))); /*ERROR*/ strcpy(walker->name, nameBuffer); } return; } I made a note of where I believe the error to be in the code above because once I added that line, I started getting it. I'm basically reading a name from a text into a nameBuffer (array) and then using strcpy to copy this name into the struct. Any advice on how to fix this? Thanks for looking. I'll include the rest of my source below: int main (void) { CASE* all; FILE* FPin; if((FPin = fopen("art.txt", "r")) == NULL) { printf("Error opening file."); exit(100); } allocateStructMem(&all); readFile(FPin, &all); fclose(FPin); return 0; } void allocateStructMem (CASE** all) { if((*all = (CASE*)malloc(sizeof(CASE)*1000)) == NULL) { printf("Fatal memory error!\n"); exit(1); } return; }

以上就是segmentation fault when trying to allocate memory for a string in a struct的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » CSS3 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏