[英]Segmentation error when trying to copy data from one struct to another
I have an ordered list of structs (CASE) by a "name" (string) field. 我有一个有序的结构列表(CASE)的“名称”(字符串)字段。 I want to create a new struct (ARTCOUNT) with parameters "name"(string) and "count"(integer). 我想创建一个带有参数“name”(字符串)和“count”(整数)的新结构(ARTCOUNT)。
Structs: 结构:
typedef struct
{
char* name;
char* art;
int rating;
}CASE;
typedef struct
{
char* name;
int count;
}ARTCOUNT;
I will walk the CASE array and if the "name" in CASE matches the name in ARTCOUNT, I will add 1 to the count, else I will create a new ARTCOUNT array with the new name and continue walking the array. 我将走CASE数组,如果CASE中的“name”与ARTCOUNT中的名称匹配,我将在计数中加1,否则我将使用新名称创建一个新的ARTCOUNT数组并继续遍历数组。
The problem I'm having is a weird segmentation fault when I try to add to the count if the names match. 当我尝试添加到计数时,如果名称匹配,我遇到的问题是一个奇怪的分段错误。
/*all is the array of CASE and pLast points to the last CASE in all*/
void countArt(CASE* all, CASE* pLast)
{
CASE* walker = all;
ARTCOUNT* artAll;
ARTCOUNT* artWalker = artAll;
ARTCOUNT* artLast;
if((artAll = (ARTCOUNT*)malloc(sizeof(ARTCOUNT)*(pLast-all+1))) == NULL)
{
printf("Fatal memory error!\n");
exit(1);
}
artWalker->name = (char*)malloc(sizeof(char)*(100));
strcpy(artWalker->name, walker->name);
artWalker->count = 1;
for(walker = all+1; walker <= pLast; walker++)
{
if (strcmp(walker->name, artWalker->name) == 0)
{
artWalker->count += 1;
}
else
{
artWalker++;
artWalker->name = (char*)malloc(sizeof(char)*(100));
strcpy(artWalker->name, walker->name);
artWalker->count = 1; //if I comment this out, no segmentation fault
}
}
artLast = artWalker;
return;
}
As mentioned in the code above, I managed to narrow down what might be the error to the line artWalker->count-1;
正如上面的代码中所提到的,我设法将可能出错的内容缩小到artWalker->count-1;
. 。 If I comment out this line, the error disappears. 如果我注释掉这一行,错误就会消失。 However, if I try to print say artWalker->name in the loop, I still get a segmentation error as well. 但是,如果我尝试在循环中打印say artWalker-> name,我仍然会收到分段错误。 I've checked over my memory allocation several times and I don't think it's that. 我已经多次查看了我的内存分配,我认为不是这样。
Any tips? 有小费吗?
ARTCOUNT* artAll;
ARTCOUNT* artWalker = artAll;
if((artAll = (ARTCOUNT*)malloc(sizeof(ARTCOUNT)*(pLast-all+1))) == NULL)
{ /* ... */ }
You are allocating the memory for artAll
after the artWalker
declaration. 您在artWalker
声明后为artAll
分配内存。 It means artWalker
is initialized with an invalid value. 这意味着artWalker
初始化为无效值。
you have declared 你宣布了
ARTCOUNT* artWalker = artAll;
and then changed artAll 然后改变了artAll
if((artAll = (ARTCOUNT*)malloc(sizeof(ARTCOUNT)*(pLast-all+1))) == NULL)
at this point artWalker is pointing to a random memory location, so it's not surprising that you get a segmentation fault 在这一点上,artWalker指向一个随机的内存位置,所以你得到一个分段错误并不奇怪
try assigning 尝试分配
artWalkr = artAll;
after malloc. 在malloc之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.