Sign in to follow this  
gamechampionx

Segmentation fault question

Recommended Posts

gamechampionx    140
I have a question regarding an error that's probably really simple to solve. This is in C++. I have the following structures: struct2 { //irrelevant info }; struct struct1 { struct2 **x }; x is used as an array of pointers. I have a void function, say a with a reference parameter: void a(struct1 &b) { .... if(b.x[i] == NULL) { ... } } What's wrong with the conditional statement? It causes segmentation faults, and I think it's because I'm not properly referencing it, but I'm not sure as to the details. It is properly allocated and should work with standard uses of arrays from testing.

Share this post


Link to post
Share on other sites
demonkoryu    980
Are you properly allocating memory to it? Like


struct1 s1;

// allocation
s1.x = new struct2*[ptr_to_array_count];
for ( int i = 0; i < ptr_to_array_count; ++i ) {
s1.x[i] = new struct2[array_size];
}

// deallocation
for ( int i = 0; i < ptr_to_array_count; ++i ) {
delete[] s1.x[i];
}
delete[] s1.x;

Share this post


Link to post
Share on other sites
nobodynews    3126
I'd need to know how you call that function, but it seems like you didn't initialize something properly so you're basically trying to access memory outside of your segment. Something could be wrong with the index variable i as well, but you don't talk about that so I can't tell. Here is what could be going wrong

struct2 alpha; // unitialized, alpha.x points to random data, ie a random location in memory
a(alpha); // almost certainly will cause a seg fault.

alpha.x[0] = 10; // what are you referencing? You haven't initialized x so you're trying to access memory that you may
// not have permission to touch

// if x is initialized
int i = 1000000; // someweird value
alpha.x[i] = 10; // you're accessing something out of the bounds of your array, this can cause a seg fault as well.


Of course without seeing more code this is just guess work.

Share this post


Link to post
Share on other sites
demonkoryu    980
Quote:
Original post by nobodynews
Of course without seeing more code this is just guess work.


Yes, code please.

Input... need more... input...
Please Polanski, can we have some more?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this