-3

I have this vector of pointers

std::vector<Connection *> List;

typedef struct {
    int Initialized;
....
} Connection;

My program is core dumping somewhere in these 5 lines. What could be the problem?

1 for ( size_t i = 0; i < List.size(); i++ ) { 
2       if ( List[i]->Initialized ) {
3           counter++ ;
4       }
5} /* for() */`  
  1. List[i] is pointing to some garbage location. so when you access List[i]->Initialized, it core dumps. Can I check for NULL here to prevent the core dump? My understanding is checking for NULL will not work as the pointer can be pointing to garbage and still be valid. So can I add some check before line 2 here, to prevent the core dump?

  2. The List.size() has a huge number,so the for loop never ends??

Am I missing some other scenarios here? we don't know what is causing this issue, so can't reproduce it. For some reason I am unable to use gdb or dbx on this system.

user1549994
  • 105
  • 1
  • 15

2 Answers2

2

So can I add some check before line 2 here, to prevent the core dump?

No, you can't check whether a pointer is valid. The way to avoid dereferencing invalid pointers is to make sure that, at every point in your code, you already know which pointers are valid and which are invalid. This may involve some combination of:

  1. Not inserting invalid pointers into the container in the first place
  2. Ensuring that any pointers that become invalid are removed from the container before or immediately after this occurs

The List.size() has a huge number,so the for loop never ends??

This would not cause a core dump.

Another possibility is that your code has some undefined behaviour so that List's memory becomes corrupted before the loop is entered.

You can use a debugger such as gdb to examine the core file and determine which instruction caused the core dump.

Brian Bi
  • 91,815
  • 8
  • 136
  • 249
1

One may initialize that particular underlying data structure with a constructor set initialized to the appropriate value.

Defining a container storing a pointer capture by a smart-pointer:

std::vector < std::shared_ptr < Connection > > list

Filling the vector is done by, e.g.,

list.push_back ( std::make_shared < Connection > ( /* arg1, arg2, ... */ );

Finally, you can simply check whether the smart-pointer of an indexn i is valid.

for ( ... )  {   
   if ( List[i] ) {
   }
}
sfrehse
  • 1,044
  • 9
  • 22