处理一个问题,即必须从文件读取数据到结构中。尝试为结构中的字符串分配内存时出现分段错误
该文件的组织方式使得有一个名字,几行ASCII艺术以#和评分结尾。下面是一个例子
Sample Name
(S)
(S)
# 5
我有我的结构设置是这样的:
typedef struct
{
char* name;
char* art;
int rating;
}CASE;
我的问题是,我不断收到一个segmentation fault
当我试图动态分配内存的代码名称的字符串如下:
/*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;
}
我做了一个记下我认为错误是上面,因为代码,一旦我说那行,我开始了。
我基本上是从文本读取一个名称到一个nameBuffer(数组),然后使用strcpy将该名称复制到结构中。有关如何解决这个问题的任何建议?
感谢您的期待。
我将列举以下我的源代码的其余部分:
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;
}