Jump to content
  • Advertisement
Sign in to follow this  
gamechampionx

Segmentation fault question

This topic is 4639 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 == 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
Advertisement
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 = new struct2[array_size];
}

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

Share this post


Link to post
Share on other sites
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 = 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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!