Hi,

I am working on a project and when I run my code, I get a segfault. I checked it with valgrind, and it says that I am trying to access a memory location that I maybe not malloc'd, stack'd or recently free'd. The only 'mysterious' thing I'm doing is, passing the pointer of a structure list to a function. Here is the code I get the segfault.

int GetFieldInt(list<fieldInfo> *listIn)
{
  list<fieldInfo>::iterator tempItr;
  int listCount = 0;

  tempItr = (*listIn).begin();
  while(tempItr != (*listIn).end())
    {
      listCount++;
      (*tempItr).percentage = ((*tempItr).percentage)*targetCount/100; //segfault here
      tempItr++;
    }
  if(listCount == 0)
    {
      cout<<"Field not defined!\n";
      return -1;
    }
  else
    return (int)MAX_RAND/listCount;
}

It's a rather long code. Whenever I pass the list pointer to a function, funny things happen. Sometimes, in the linux terminal, the font changes to some weird symbols. Can anyone help me with this?

Your help is much appreciated. Thanks in advance.

Thilan

Recommended Answers

All 3 Replies

Ok first of all: Why are you passing this list as pointer and not a const&? You are not modifying the passed list in any way...
If you insist on using a pointer to pass it, we need to see how you're calling this function to be able to see what's wrong.

Thanks for the reply. In fact, I am modifying the list in the following line:

(*tempItr).percentage = ((*tempItr).percentage)*targetCount/100; //segfault here

The list I'm passing is a global variable in main. This method is in a different file and I extern to use the list. Following is the function call:

vlanPriorityInt = GetFieldInt(&vlanPriority)

Thank you

I figured it out. The lists that I am using are used iteratively. At the beginning of each iteration, they should be empty. But I forgot to clear them at the end of the iteration. So they got augmented each iteration which caused the segfault.

Now it's working fine. Thanks 'thelamb' for your reply.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.