Huy
Huy

Reputation: 11206

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. I want to create a new struct (ARTCOUNT) with parameters "name"(string) and "count"(integer).

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.

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;. 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. I've checked over my memory allocation several times and I don't think it's that.

Any tips?

Upvotes: 1

Views: 173

Answers (2)

Spot
Spot

Reputation: 83

you have declared

ARTCOUNT* artWalker = artAll;

and then changed 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

try assigning

artWalkr = artAll;

after malloc.

Upvotes: 1

ouah
ouah

Reputation: 145839

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. It means artWalker is initialized with an invalid value.

Upvotes: 3

Related Questions