C++ Pointers/Segfault... why?

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

C++ Pointers/Segfault... why?

Post by Chris Corbyn »

Is this something to do with the fact I used a global pointer then assigned it to something that was only declared in the scope of the function?

Code: Select all

int arrayLength = 0;
struct myStruct
{
    int a;
    int b;
    string foo;
};
list<myStruct> myList;
myStruct *myArray; //Watch this space
int myArrayLength = 0;

void myFunc();

//Start doing stuff

int main()
{
    myFunc(); //Run that function below to build "myArray"
    for (int i = 0; i < myArrayLength; i++) cout << myArray[i].foo << endl; //Prints a few values then segfaults!! 
}

void myFunc()
{
    ifstream myFile('./somefile'); //We don't know how many lines are in the file yet
    while (!myFile.eof())
    {
        string tmp;
        getline(myFile, tmp);
        myStruct x;
        x.a = 10; //Just any value
        x.b = 6; //Some other value
        x.foo = tmp;
        myList.push_back(x); //Add to stack
        myArrayLength++; //Keep track of how many records we get
    }
    /*
      So now we have a list that has data about our file
      */
    myStruct bar[myArrayLength]; //Declare a new array of correct size
    list<myStruct>::iterator i;
    int z = 0;
    for (i = myList.begin(); i != myList.end(); i++)
    {
        bar[z] = (*i); //Copy to the array
        z++;
    }
    
    myArray = bar; //This is where it seems to go wrong!!! 

    /*
     Print out all of "myArray" just to see that it really is there at this point in execution
     */
    for (int i = 0; i < myArrayLength; i++)  cout << myArray[i].foo << endl; //This does work
};
Basically I'm trying to optimize some code that uses a stl::list by moving the contents back out of the list into an array before starting the heavy work (arrays are faster, but I'm not sure by how much since I can't get it working).

I know the segfault must have something to do with the scope of that pointer but how can I work around that?

Cheers :D
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Re: C++ Pointers/Segfault... why?

Post by timvw »

d11wtq wrote:Is this something to do with the fact I used a global pointer then assigned it to something that was only declared in the scope of the function?
You point myArray to an address of a variable that exists only in myFunc... Thus once you're outside that function, myArray points to something bogus..

(probably there are some compiler options to make variables live longer than their scope... i think microsoft used to provide such compilers :p but i'm not really convinced that it's a good thing to have)

If you like to read: http://cplus.about.com/od/beginnerctuto ... 01902a.htm
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: C++ Pointers/Segfault... why?

Post by Chris Corbyn »

timvw wrote:
d11wtq wrote:Is this something to do with the fact I used a global pointer then assigned it to something that was only declared in the scope of the function?
You point myArray to an address of a variable that exists only in myFunc... Thus once you're outside that function, myArray points to something bogus..

(probably there are some compiler options to make variables live longer than their scope... i think microsoft used to provide such compilers :p but i'm not really convinced that it's a good thing to have)
Thanks.

So what would be the normal way of creating an array at runtime, for the fact you don't know how big it will be in advance? The stl::list itself is a big help and my program runs nicely without an array but it's taking a long time to parse large scripts. From what I've read linked lists are slow because to access data they itreate across all previous items first. That's why I'm trying to convert it into an array before I start doing an heavy processing with it.

Basically the array goes into a loop lots and lots of times in order to generate some output.

Can I increase the size (efficiently and accurately) of an array "myStruct foo[1]" at runtime. I guess malloc() will work but I've never really understood how you know precisely how much space to allocated with malloc :( This weekend has been a steep learning curve for me :P
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Damn, I'm getting rusty.

Code: Select all

myArray = new myStruct[myArrayLength];

...

delete [] myArray;
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

If you're only adding/removing at the beginning and end you might want to try a stl::deque instead, for random access you could try stl::vector...
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: C++ Pointers/Segfault... why?

Post by alex.barylski »

timvw wrote:
d11wtq wrote:Is this something to do with the fact I used a global pointer then assigned it to something that was only declared in the scope of the function?
You point myArray to an address of a variable that exists only in myFunc... Thus once you're outside that function, myArray points to something bogus..

(probably there are some compiler options to make variables live longer than their scope... i think microsoft used to provide such compilers :p but i'm not really convinced that it's a good thing to have)

If you like to read: http://cplus.about.com/od/beginnerctuto ... 01902a.htm
Huh...never heard of such a thing... :?

If you find out otherwise, please send me the link...

As far as I know and remember, the only way to persist a variable longer than it's scope it to create a variable on the heap instead of the stack...

Variables on the stack get popped immediately (regardless of compiler settings) when it they go out of scope...

Variables on the heap...however stay there until explicitly deleted via delete

Cheers :)
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: C++ Pointers/Segfault... why?

Post by alex.barylski »

d11wtq wrote:
timvw wrote:
d11wtq wrote:Is this something to do with the fact I used a global pointer then assigned it to something that was only declared in the scope of the function?
You point myArray to an address of a variable that exists only in myFunc... Thus once you're outside that function, myArray points to something bogus..

(probably there are some compiler options to make variables live longer than their scope... i think microsoft used to provide such compilers :p but i'm not really convinced that it's a good thing to have)
Thanks.

So what would be the normal way of creating an array at runtime, for the fact you don't know how big it will be in advance? The stl::list itself is a big help and my program runs nicely without an array but it's taking a long time to parse large scripts. From what I've read linked lists are slow because to access data they itreate across all previous items first. That's why I'm trying to convert it into an array before I start doing an heavy processing with it.

Basically the array goes into a loop lots and lots of times in order to generate some output.

Can I increase the size (efficiently and accurately) of an array "myStruct foo[1]" at runtime. I guess malloc() will work but I've never really understood how you know precisely how much space to allocated with malloc :( This weekend has been a steep learning curve for me :P
STL would likely be the way to go, because direct memory managment is how VERY hard to find bugs are created :)

The STL vector is the way to go for fast random access...it doesn't implement anything fancy, it's simply a container class for a linear array.

You are correct in your thinking about linked lists, they are slow for things like random access, because of the way they are implemented. Basically structures with previous and next pointers. Making them awesome for random insertion/deletion (which are constant in time) but slow as melting polar ice caps for indexing.

Anyways, use a vector if you want dynamic array allocation...

http://www.sgi.com/tech/stl/Vector.html

Cheers :)
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Thanks Hockey. Yeah I was using a STL vector and I gathered that the reason for them being slower was due to the double-linking/iteration. Since i'm always looping over the list in a linear fashion due to the nature of the way the app works maybe a basic array wouldn't be any faster in any case.

As for compiler options I believe GNU's g++ compiler/linker (linux of course) offers some scope options (I've heard this from 3 people now) but I haven't looked into it.... it has to be a BAD idea in any case.... I'd have lots of identifier changing to do :?
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

d11wtq wrote:Thanks Hockey. Yeah I was using a STL vector and I gathered that the reason for them being slower was due to the double-linking/iteration. Since i'm always looping over the list in a linear fashion due to the nature of the way the app works maybe a basic array wouldn't be any faster in any case.

As for compiler options I believe GNU's g++ compiler/linker (linux of course) offers some scope options (I've heard this from 3 people now) but I haven't looked into it.... it has to be a BAD idea in any case.... I'd have lots of identifier changing to do :?
I suppose technically it's possible, but seems very illogical and almost completely useless :?

All my development is strictly Windows, so perhaps I'm keeping a biased view here...

There may very well be reasons on *nix machines to keep a local variable "alive" outside of it's scope, in which case, why not make it explicit using static?

I think I'm missing something here... :D

Cheers :)
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Eg: with the visual c++ 6 compiler the following code is perfectly acceptable, notice that i is still defined in the second loop.
With visual c++ 8 you explicitely have to disable a check for conformance to get the code compiled.

Code: Select all

for (int i = 0; i < 10; ++i) { ; }
for (i = 0; i < 10; ++i) { ; }
Post Reply