0

I have a seg fault in C++ when entering a for loop. But I mean when ENTERING IT. Here is the code I'm running:

std::cout<<"forcing order"<<endl;
std::cout<<"crossoverPointNumber = "<<crossoverPointNumber<<endl;
for (long j=0; j<crossoverPointNumber; j++)
{
    std::cout<<"j = "<<j<<". ";
    offsprings[1][positionsInParent1[j]] = valuesInParent2[j];  // Forces the order
}//end for j

The output I get on the terminal is:

forcing order
crossoverPointNumber = 4
Segmentation fault

Can anyone explain to me what am I missing here?? it seems to be either very elementary or very complex C++ stuff...

8
  • 1
    You're most likely accessing something out of its bounds. Impossible to tell with just what you posted here. (Use a debugger, your program most likely isn't aborting on the first line of the loop but on the second.) Commented Mar 6, 2012 at 10:05
  • "it seems to be either very elementary or very complex C++ stuff...", more like the elementaray :) Provide some more code about the declaration/initialization of offsprings Commented Mar 6, 2012 at 10:07
  • but then why is the line std::cout<<"j = "<<j<<". "; not printing? Commented Mar 6, 2012 at 10:07
  • Also: is offsprings[1] intended? Do you want to access the first element? You'd have to write offsprings[0], since C arrays are zero-based. Commented Mar 6, 2012 at 10:08
  • 1
    @user1251858 That cout line won't be printing because you aren't adding an endl. The output is buffered. Commented Mar 6, 2012 at 10:09

1 Answer 1

3

You aren't adding an endl to the cout stream in your loop, so the code you've posted doesn't tell us when you are getting the segmentation fault. Until you add an endl the output stream won't be flushed.

I would strongly suspect that you are running off the end of your positionsInParent1 or valuesInParent2 arrays.

Sign up to request clarification or add additional context in comments.

2 Comments

yep, you guys were right, I added endl and it printed went back, looked at the code, forgot to initialize offsprings[1]. sorry for the n00bness
@user1251858 If you learn how to use a debugger, you will go a very long way. Not only will it help you catch these bugs and fix them sooner, it'll help you understand better how your code works in general by tracing through it with the aid of debugging tools.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.