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;
}
strlen(nameBuffer+1)You also have to do something like this when you malloc
all:To prevent overflow you have to limit the length of
fscanf, ie:The
1ensure you have actually read something into nameBuffer.Also
strcpydoes not pad – but you might know that.