karlkar
karlkar

Reputation: 227

Struct creation issue

I have a struct declared like this:

struct sExample {
  int something;
  char somethingElse[32];
  bool another;
  // many other fields
};

It has more of int, char[] and bool. Now let's face the problem. First of all I created a class which uses temporary variable of type sExample.

class ExClass {
  void fun() {
    sExample myStruct;
    // Initialize some of the struct fields (just some of them!)
    strcpy(myStruct.somethingElse, "TEXT");
    // Use struct in function that may read or modify it
    globalFunction(&myStruct);
  }
}

It worked just fine, but later I decided that myStruct should be available longer then just in function fun, so I moved it to class members:

class ExClass {
  sExample myStruct;
  void fun() {
    // Same code as above
    // Initialize some of the struct fields (just some of them!)
    strcpy(myStruct.somethingElse, "TEXT");
    // Use struct in function that may read or modify it
    globalFunction(&myStruct);
  }
}

And here is the problem. Call to globalFunction causes segfault (this is a function from an external 3rd party library, so I can't identify where exactly the problem is). I've also tried initializing struct with use of = {0}, but it didn't help. What can be wrong? I'm using Gcc 4.9, C++11. Anybody can explain what is the problem here?

Upvotes: 2

Views: 82

Answers (1)

huysentruitw
huysentruitw

Reputation: 28111

If that is your only change, then your issue is that you're calling fun() on a invalid instance of ExClass. Or you forgot to new the class or it already is deleted/went out of scope.

F.e. this Ideone example works perfectly, because A a is created on stack inside fun(). But once you move the declaration of a to class level, you will get an exception because *b is not instantiated.

#include <iostream>
using namespace std;

struct A {
    int data;
    A() : data(123) { }
};

class B {
public:
    void fun() {
        A a;
        cout << a.data;
    }
};

int main() {
    B* b; // b points to random memory, thus is an invalid instance
    b->fun(); // this still works because fun doesn't access any member of B
    return 0;
}

Upvotes: 2

Related Questions