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
( S )
( S )
I have my struct set up like this:
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* bufferPtr = buffer;
/*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*/
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)
if((FPin = fopen("art.txt", "r")) == NULL)
printf("Error opening file.");
void allocateStructMem (CASE** all)
if((*all = (CASE*)malloc(sizeof(CASE)*1000)) == NULL)
printf("Fatal memory error!\n");
以上就是segmentation fault when trying to allocate memory for a string in a struct的详细内容，更多请关注web前端其它相关文章！