most puzzling seg fault bug
I have a wierd situation. When I add a new var to the main(){} of my program I get a seg fault error. So if I was to add this to the code below: int myNewVar = 0;
I would get a seg fault, otherwise program is fine. Any help would be awesome I have been fighting this for some time now. Thanks Code:
#include <iostream> |
You seems to have uninitalized variables in 'main':
Code:
float *ptr_wait; Code:
float ptr_wait = 0; |
Quote:
Correcting all those uses, so each variable is a float within main() but a float* everywhere else, is a bit more efficient than the alternative I'm about to suggest. But the following is less of a change and it keeps the usage consistent between main() and the rest of the code, which may make the program more maintainable. Instead of: Code:
float *ptr_wait; Code:
float val_wait=0 The efficient solution (in some more advanced cases the only good solution) is to use an XYZ (instead of an XYZ*) within the top level function and pass &name instead of name to any function that needs an XYZ* The simplest solution, as I showed above, is to declare and initialize an XYZ and use its address to initialize the pointer. The common solution is to use malloc. Sometime that is best, but it is more popular (as compared to the simpler solution) than it ought to be. Code:
float* ptr_wait = (float*)malloc( sizeof(float) ); Code:
float* ptr_wait = new float(0); |
Thank you very much! That was the problem. Do you know why it was that only when I added a new variable that I would get the seg fault?
|
Those non-initialized variables have usually got a something like a random value. The memory area of those variables were earlier in use (probably). Adding another variable will cause only one thing, the variables will be stored in another part of the memory, therefore will get another "initial" value. So in your example in the first case the memory contained something usable, and in the second case the memory (where those variables were stored) contained invalid values.
|
I see, thank you.
|
All times are GMT -5. The time now is 07:28 PM. |