Re: C++ - Pointer to Structure leads to segfault
On 2009-01-13 22:18, dmangal wrote:
Hi all...first time poster, long time reader.
I've been experiencing some strange behavior on a Linux development
system (Red Hat 5) compiling a C++ App. I've tried to reduce the
source to something as simple as possible so that I can fit all source
that would still causes my problem. Below are the three simple source
files for class FooClass:
FooClass.hpp:
class FooClass
{
public:
void fooMethod();
private:
typedef struct {
int fooData;
} FooStruct;
C-ism, in C++ you don't need the typedef:
struct FooStruct {
int fooData;
};
FooClass.cpp:
#include "FooClass.hpp"
void FooClass::fooMethod()
{
FooStruct* foo;
You create a pointer to a FooStruct, but you do not initialise it to
anything, so it could point to just about anything.
foo->fooData = 5;
And here you take the piece of memory that the pointer happens to point
to and try to treat it as if it pointed to a FooStruct object.
You forgot to initialise the pointer, replace the FooStruct* foo; line
with this:
FooStruct* foo = new FooStruct();
Oh...and for a side note, this runs with no problem on a different
system running an older version of Linux (Red Hat 4).
Just luck. I suppose a change in RH5 caused to pointer to be initialised
to a different value which happens to point to a unallocated address
while in RH4 you were lucky and the pointer pointed to some allocated
memory.
--
Erik Wikstr??m