Using NaN value in MSChart gives Overflow Exception - mschart

I'm working in a real time ploting appication with MSChart...I need to set some y values to NaN but I'm getting an overflow exception. Here is the part of the code where it happen:
if (j_ecg < 2569)
{
for (int i = 0; i < 32; i++)
{
this.Invoke((MethodInvoker)delegate
{
ECG.Points.AddXY(puntos_ecg[j_ecg].X,puntos_ecg[j_ecg].Y);
});
j_ecg++;
}
}
else
{
for (int i = 0; i < 32; i++)
{
this.Invoke((MethodInvoker)delegate
{
ECG.Points[ecg_s].SetValueY(puntos_ecg[j_ecg].Y);
for (int j = 1; j < 10; j++){ ECG.Points[ecg_s + j].SetValueY(double.NaN); }
});
j_ecg++;
ecg_s++;
if (ecg_s == 2560) { ecg_s = 0; }
}
}
The Invokes are there to avoid cross threads issues.
Any idea of how can I do it for not getting the exception? I've try using unchecked keyword just before the SetValueY call but nothing changes.

First thing to try is disabling autoscaling so that min/max don't need to be calculated:
chart1.ChartAreas["Default"].AxisY.Minimum = <your min>;
chart1.ChartAreas["Default"].AxisY.Maximum = <your max>;
However you still need to have at least one real value in one of your series.
I recommend you keep track of your displayed values. If everything is NaN, stop plotting! When the next valid value comes in resume plotting.
Note: using zeroes instead of NaN is another solution.

Related

Why is my output freezing when it gets to this section of the code?

I'm trying to compare two decks of cards, yet every time I try another method of doing it, I get the same result... Everything before the code outputs, and it just freezes as soon as it hits the comparison code, as if it's stuck in an infinite loop.
I've tried for loops, static variables, do-while loops, etc. This is my first time leaving the loop at the client code.
The code that supposedly throws the program into an infinite loop.
while (repeatLoop == false)
{
deck1.shuffleDeck();
counter++;
repeatLoop = deck1.compareDecks();
}
compareDecks function.
bool deck::compareDecks()
{
int deckCount = 0;
suitType tempOriginalSuit;
suitType tempShuffleSuit;
rankType tempOriginalRank;
rankType tempShuffleRank;
while (index < 52)
{
tempOriginalSuit = originalCardDeck[index].getSuit();
tempShuffleSuit = shuffledCardDeck[index].getSuit();
if (int(tempOriginalSuit) == int(tempShuffleSuit))
{
tempOriginalRank = originalCardDeck[index].getRank();
tempShuffleRank = shuffledCardDeck[index].getRank();
if (int(tempOriginalRank) == int(tempShuffleRank))
{
deckCount++;
if (deckCount == 52)
return true;
}
}
else
{
return false;
index++;
}
}
}
The shuffleDeck function
(This function pushes back the first card from the first half of the deck and the first card from the second half of the deck towards the end until all 52 cards have been pushed in this pattern. This makes the deck have 52 x 2 cards (with the second half of the deck being the perfect shuffle), so I delete the first half of the cards using .erase as it is not needed)
void deck::shuffleDeck()
{
for (int a = 0, b = 2; a < 2 && b < 4; a++, b++)
{
for (int i = 2; i < 15; i++)
{
shuffledCardDeck.push_back(card{ static_cast<cardSpace::suitType>(a),
static_cast<cardSpace::rankType>(i) });
shuffledCardDeck.push_back(card{ static_cast<cardSpace::suitType>(b),
static_cast<cardSpace::rankType>(i) });
}
}
shuffledCardDeck.erase(shuffledCardDeck.begin(),
shuffledCardDeck.begin() + (shuffledCardDeck.size() / 2));
}
The two decks initialized by this constructor.
deck::deck()
{
for (int i = 0; i < 4; i++)
{
for (int j = 2; j < 15; j++)
{
originalCardDeck.push_back(card{ static_cast<cardSpace::suitType>(i),
static_cast<cardSpace::rankType>(j) });
shuffledCardDeck.push_back(card{ static_cast<cardSpace::suitType>(i),
static_cast<cardSpace::rankType>(j) });
}
}
}
Also note that I've done a perfect shuffle on the shuffledCardDeck vector in another function. I'm trying to repeat the perfectShuffle function until it reaches it's original state and output how many times it took to do this.
I get an infinite loop.
EDIT: I've decided to add the return false; statement in the compareDecks function into the if-else. Also, I think what's causing the problem is that my index i is reset to zero everytime it is called again. Are there any solutions you guys could propose to this? I've tried using static variables, but they just would not increment in the for loop.
EDIT 2: I enclosed my if statements within the curly braces, per users' request, as it's a flaw in my code.
EDIT 3: After commenting out
deck1.shuffleDeck()
The compareDecks function returned true, stating that the decks are equal, which isn't supposed to happen... This caused the loop to end after only one loop.
I was expecting you to actually shuffle the deck.
Your code was pushing a specific, newly synthesized card onto the end of the deck:
shuffledCardDeck.push_back(card{ static_cast<cardSpace::suitType>(a),
static_cast<cardSpace::rankType>(i) });
For example, the first card it will push is always the 2 of 0's (Whatever the 0th suit is). That's not what you want. You actually want to push a copy of the card that is at a specific position index in the deck. For example, loop index from 0 to 25 and then push shuffledCardDeck[index] and shuffledCardDeck[26 + index].
Then you can still wrap up by using your technique of erasing the first half of the deck.
void deck::shuffleDeck()
{
for (int index = 0; index < 26; ++index) {
shuffledCardDeck.push_back(shuffledCardDeck[index]);
shuffledCardDeck.push_back(shuffledCardDeck[26 + index]);
}
shuffledCardDeck.erase(shuffledCardDeck.begin(),
shuffledCardDeck.begin() + 52);
}
You are not modifying the value in the loop, you're using a double equals sign:
repeatLoop == deck1.compareDecks();
That would explain your observed behavior.

How to avoid use of goto and break nested loops efficiently

I'd say that it's a fact that using goto is considered a bad practice when it comes to programming in C/C++.
However, given the following code
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; j++)
{
for (k = 0; k < N; ++k)
{
...
if (condition)
goto out;
...
}
}
}
out:
...
I wonder how to achieve the same behavior efficiently not using goto. What i mean is that we could do something like checking condition at the end of every loop, for example, but AFAIK goto will generate just one assembly instruction which will be a jmp. So this is the most efficient way of doing this I can think of.
Is there any other that is considered a good practice? Am I wrong when I say it is considered a bad practice to use goto? If I am, would this be one of those cases where it's good to use it?
Thank you
The (imo) best non-goto version would look something like this:
void calculateStuff()
{
// Please use better names than this.
doSomeStuff();
doLoopyStuff();
doMoreStuff();
}
void doLoopyStuff()
{
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; j++)
{
for (k = 0; k < N; ++k)
{
/* do something */
if (/*condition*/)
return; // Intuitive control flow without goto
/* do something */
}
}
}
}
Splitting this up is also probably a good idea because it helps you keep your functions short, your code readable (if you name the functions better than I did) and dependencies low.
If you have deeply-nested loops like that and you must break out, I believe that goto is the best solution. Some languages (not C) have a break(N) statement that will break out of more than one loop. The reason C doesn't have it is that it's even worse than a goto: you have to count the nested loops to figure out what it does, and it's vulnerable to someone coming along later and adding or removing a level of nesting, without noticing that the break count needs to be adjusted.
Yes, gotos are generally frowned upon. Using a goto here is not a good solution; it's merely the least of several evils.
In most cases, the reason you have to break out of a deeply-nested loop is because you're searching for something, and you've found it. In that case (and as several other comments and answers have suggested), I prefer to move the nested loop to its own function. In that case, a return out of the inner loop accomplishes your task very cleanly.
(There are those who say that functions must always return at the end, not from the middle. Those people would say that the easy break-it-out-to-a-function solution is therefore invalid, and they'd force the use of the same awkward break-out-of-the-inner-loop technique(s) even when the search was split off to its own function. Personally, I believe those people are wrong, but your mileage may vary.)
If you insist on not using a goto, and if you insist on not using a separate function with an early return, then yes, you can do something like maintaining extra Boolean control variables and testing them redundantly in the control condition of each nested loop, but that's just a nuisance and a mess. (It's one of the greater evils that I was saying using a simple goto is lesser than.)
I think that goto is a perfectely sane thing to do here, and is one of it's exceptional use cases per the C++ Core Guidelines.
However, perhaps another solution to be considered is an IIFE lambda. In my opinion this is slightly more elegant than declaring a separate function!
[&] {
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; ++k)
if (condition)
return;
}();
Thanks to JohnMcPineapple on reddit for this suggestion!
In this case you don't wan't to avoid using goto.
In general the use of goto should be avoided, however there are exceptions to this rule, and your case is a good example of one of them.
Let's look at the alternatives:
for (i = 0; i < N; ++i) {
for (j = 0; j < N; j++) {
for (k = 0; k < N; ++k) {
...
if (condition)
break;
...
}
if (condition)
break;
}
if (condition)
break;
}
Or:
int flag = 0
for (i = 0; (i < N) && !flag; ++i) {
for (j = 0; (j < N) && !flag; j++) {
for (k = 0; (k < N) && !flag; ++k) {
...
if (condition) {
flag = 1
break;
...
}
}
}
Neither of these is as concise or as readable as the goto version.
Using a goto is considered acceptable in cases where you're only jumping ahead (not backward) and doing so makes your code more readable and understandable.
If on the other hand you use goto to jump in both directions, or to jump into a scope which could potentially bypass variable initialization, that would be bad.
Here's a bad example of goto:
int x;
scanf("%d", &x);
if (x==4) goto bad_jump;
{
int y=9;
// jumping here skips the initialization of y
bad_jump:
printf("y=%d\n", y);
}
A C++ compiler will throw an error here because the goto jumps over the initialization of y. C compilers however will compile this, and the above code will invoke undefined behavior when attempting to print y which will be uninitialized if the goto occurs.
Another example of proper use of goto is in error handling:
void f()
{
char *p1 = malloc(10);
if (!p1) {
goto end1;
}
char *p2 = malloc(10);
if (!p2) {
goto end2;
}
char *p3 = malloc(10);
if (!p3) {
goto end3;
}
// do something with p1, p2, and p3
end3:
free(p3);
end2:
free(p2);
end1:
free(p1);
}
This performs all of the cleanup at the end of the function. Compare this to the alternative:
void f()
{
char *p1 = malloc(10);
if (!p1) {
return;
}
char *p2 = malloc(10);
if (!p2) {
free(p1);
return;
}
char *p3 = malloc(10);
if (!p3) {
free(p2);
free(p1);
return;
}
// do something with p1, p2, and p3
free(p3);
free(p2);
free(p1);
}
Where the cleanup is done in multiple places. If you later add more resources that need to be cleaned up, you have to remember to add the cleanup in all of these places plus the cleanup of any resources that were obtained earlier.
The above example is more relevant to C than C++ since in the latter case you can use classes with proper destructors and smart pointers to avoid manual cleanup.
Lambdas let you create local scopes:
[&]{
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; j++)
{
for (k = 0; k < N; ++k)
{
...
if (condition)
return;
...
}
}
}
}();
if you also want the ability to return out of that scope:
if (auto r = [&]()->boost::optional<RetType>{
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; j++)
{
for (k = 0; k < N; ++k)
{
...
if (condition)
return {};
...
}
}
}
}()) {
return *r;
}
where returning {} or boost::nullopt is a "break", and returning a value returns a value from the enclosing scope.
Another approach is:
for( auto idx : cube( {0,N}, {0,N}, {0,N} ) {
auto i = std::get<0>(idx);
auto j = std::get<1>(idx);
auto k = std::get<2>(idx);
}
where we generate an iterable over all 3 dimensions and make it a 1 deep nested loop. Now break works fine. You do have to write cube.
In c++17 this becomes
for( auto[i,j,k] : cube( {0,N}, {0,N}, {0,N} ) ) {
}
which is nice.
Now, in an application where you are supposed to be responsive, looping over a large 3 dimensional range at primiary control flow level is often a bad idea. You can thread it off, but even then you end up with problem that the thread runs too-long. And most 3 dimensional large iterations I've played with can benefit from using sub-task threading themselves.
To that end, you'll end up wanting to categorize your operation based on what kind of data it accesses, then pass your operation to something that schedules the iteration for you.
auto work = do_per_voxel( volume,
[&]( auto&& voxel ) {
// do work on the voxel
if (condition)
return Worker::abort;
else
return Worker::success;
}
);
then the control flow involved goes into the do_per_voxel function.
do_per_voxel isn't going to be a simple naked loop, but rather a system to rewrite the per-voxel tasks into per-scanline tasks (or even per-plane tasks depending on how large the planes/scanlines are at runtime (!)) then dispatch them in turn to a thread pool managed task scheduler, stitch up the resulting task handles, and return a future-like work that can be awaited on or used as a continuation trigger for when the work is done.
And sometimes you just use goto. Or you manually break out functions for subloops. Or you use flags to break out of deep recursion. Or you put the entire 3 layer loop in its own function. Or you compose the looping operators using a monad library. Or you can throw an exception (!) and catch it.
The answer to almost every question in c++ is "it depends". The scope of problem and the number of techniques you have available is large, and the details of the problem change the details of the solution.
Alternative - 1
You can do something like follows:
Set a bool variable in the beginning isOkay = true
All of your forloop conditions, add an extra condition isOkay == true
When your your custom condition is satisfied/ fails, set isOkay = false.
This will make your loops stop. An extra bool variable would be sometimes handy though.
bool isOkay = true;
for (int i = 0; isOkay && i < N; ++i)
{
for (int j = 0; isOkay && j < N; j++)
{
for (int k = 0; isOkay && k < N; ++k)
{
// some code
if (/*your condition*/)
isOkay = false;
}
}
}
Alternative - 2
Secondly. if the above loop iterations are in a function, best choice is to return result, when ever the custom condition is satisfied.
bool loop_fun(/* pass the array and other arguments */)
{
for (int i = 0; i < N ; ++i)
{
for (int j = 0; j < N ; j++)
{
for (int k = 0; k < N ; ++k)
{
// some code
if (/* your condition*/)
return false;
}
}
}
return true;
}
Break your for loops out into functions.
It makes things significantly easier to understand because now you can see what each loop is actually doing.
bool doHerpDerp() {
for (i = 0; i < N; ++i)
{
if (!doDerp())
return false;
}
return true;
}
bool doDerp() {
for (int i=0; i<X; ++i) {
if (!doHerp())
return false;
}
return true;
}
bool doHerp() {
if (shouldSkip)
return false;
return true;
}
Is there any other that is considered a good practice? Am I wrong when
I say it is considered a bad practice to use goto?
goto can be misused and overused, but I dont see any of the two in your example. Breaking out of a deeply nested loop is most clearly expressed by a simple goto label_out_of_the_loop;.
It is bad practice to use many gotos that jump to different labels, but in such cases it isnt the keyword goto itself that makes your code bad. It is the fact that you are jumping around in the code making it hard to follow that makes it bad. If however, you need a single jump out of nested loops then why not use the tool that was made for exactly that purpose.
To use a made up out of thin air analogy: Imagine you live in a world where in the past it was hip to hammer nails into walls. In recent times it became more fashinable to drill screws into walls using screwdrivers and hammers are completely out of fashion. Now consider you have to (despite being a bit old-fashinoned) get a nail into a wall. You should not refrain from using a hammer to do that, but maybe you should rather ask yourself if you really need a nail in the wall instead of a screw.
(Just in case it isnt clear: The hammer is goto and the nail in the wall is a jump out of a nested loop while the screw in the wall would be using functions to avoid the deep nesting alltogether ;)
One possible way is to assign a boolean value to a variable that represents the state. This state can later be tested using an "IF" conditional statement for other purposes later on in the code.
as far as your comment on efficiency compiling the both options in release mode on visual studio 2017 produces the exact same assembly.
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
for (int k = 0; k < 5; ++k)
{
if (i == 1 && j == 2 && k == 3) {
goto end;
}
}
}
}
end:;
and with a flag.
bool done = false;
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
for (int k = 0; k < 5; ++k)
{
if (i == 1 && j == 2 && k == 3) {
done = true;
break;
}
}
if (done) break;
}
if (done) break;
}
both produce..
xor edx,edx
xor ecx,ecx
xor eax,eax
cmp edx,1
jne main+15h (0C11015h)
cmp ecx,2
jne main+15h (0C11015h)
cmp eax,3
je main+27h (0C11027h)
inc eax
cmp eax,5
jl main+6h (0C11006h)
inc ecx
cmp ecx,5
jl main+4h (0C11004h)
inc edx
cmp edx,5
jl main+2h (0C11002h)
so there is no gain. Another option if your using a modern c++ compiler is to wrap it in a lambda.
[](){
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
for (int k = 0; k < 5; ++k)
{
if (i == 1 && j == 2 && k == 3) {
return;
}
}
}
}
}();
again this produces the exact same assembly. Personally I think using goto in your example is perfectly acceptable. It is clear what is happening to anyone else, and makes for more concise code. Arguably the lambda is equally as concise.
Specific
IMO, in this specific example, I think it is important to notice a common functionality between your loops. (Now I know that your example isn't necessarily literal here, but just bear with me for a sec) as each loop iterates N times, you can restructure your code like the following:
Example
int max_iterations = N * N * N;
for (int i = 0; i < max_iterations; i++)
{
/* do stuff, like the following for example */
*(some_ptr + i) = 0; // as opposed to *(some_3D_ptr + i*X + j*Y + Z) = 0;
// some_arr[i] = 0; // as oppose to some_3D_arr[i][j][k] = 0;
}
Now, it is important to remember that all loops, while for or otherwise, are really just syntatic sugar for the if-goto paradigm. I agree with the others that you ought to have a function return the result, however I wanted to show an example like the above in which that may not be the case. Granted, I'd flag the above in a code review but if you replaced the above with a goto I'd consider that a step in the wrong direction. (NOTE -- Make sure that you can reliably fit it into your desired datatype)
General
Now, as a general answer, the exit conditions for your loop may not be the same everytime (like the post in question). As a general rule, pull as many unneeded operations out of your loops (multiplications, etc.) as far out as you can as, while compilers are getting smarter everyday, there is no replacement for writing efficient and readable code.
Example
/* matrix_length: int of m*n (row-major order) */
int num_squared = num * num;
for (int i = 0; i < matrix_length; i++)
{
some_matrix[i] *= num_squared; // some_matrix is a pointer to an array of ints of size matrix_length
}
rather than writing *= num * num, we no longer have to rely on the compiler to optimize this out for us (though any good compiler should). So any doubly or triply nested loops which perform the above functionality would also benefit not only your code, but IMO writing clean and efficient code on your part. In the first example, we could have instead had *(some_3D_ptr + i*X + j*Y + Z) = 0;! Do we trust the compiler to optimize out i*X and j*Y, so that they aren't computed every iteration?
bool check_threshold(int *some_matrix, int max_value)
{
for (int i = 0; i < rows; i++)
{
int i_row = i*cols; // no longer computed inside j loop unnecessarily.
for (int j = 0; j < cols; j++)
{
if (some_matrix[i_row + j] > max_value) return true;
}
}
return false;
}
Yuck! Why aren't we using classes provided by the STL or a library like Boost? (we must be doing some low level/high performant code here). I couldn't even write a 3D version, due to the complexity. Even though we have hand optimized something, it may even be better to use #pragma unroll or similar preprocessor hints if your compiler allows.
Conclusion
Generally, the higher the abstraction level you can use, the better, however if say aliasing a 1-Dimensional row-major order matrix of integers to a 2-Dimensional array makes your code-flow harder to understand/extend, is it worth it? Likewise, that also may be an indicator to make something into its own function. I hope that, given these examples, you can see that different paradigms are called for in different places, and its your job as the programmer to figure that out. Don't go crazy with the above, but make sure you know what they mean, how to use them, and when they are called for, and most importantly, make sure the other people using your codebase know what they are as well and have no qualms about it. Good luck!
bool meetCondition = false;
for (i = 0; i < N && !meetCondition; ++i)
{
for (j = 0; j < N && !meetCondition; j++)
{
for (k = 0; k < N && !meetCondition; ++k)
{
...
if (condition)
meetCondition = true;
...
}
}
}
There are already several excellent answers that tell you how you can refactor your code, so I won’t repeat them. There isn’t a need to code that way for efficiency any more; the question is whether it’s inelegant. (Okay, one refinement I’ll suggest: if your helper functions are only ever intended to be used inside the body of that one function, you might help the optimizer out by declaring them static, so it knows for certain that the function does not have external linkage and will never be called from any other module, and the hint inline can’t hurt. However, previous answers say that, when you use a lambda, modern compilers don’t need any such hints.)
I’m going to challenge the framing of the question a bit. You’re correct that most programmers have a taboo against using goto. This has, in my opinion, lost sight of the original purpose. When Edsger Dijkstra wrote, “Go To Statement Considered Harmful,” there was a specific reason he thought so: the “unbridled” use of go to makes it too hard to reason formally about the current program state, and what conditions must currently be true, compared to control flow from recursive function calls (which he preferred) or iterative loops (which he accepted). He concluded:
The go to statement as it stands is just too primitive; it is too much an invitation to make a mess of one's program. One can regard and appreciate the clauses considered as bridling its use. I do not claim that the clauses mentioned are exhaustive in the sense that they will satisfy all needs, but whatever clauses are suggested (e.g. abortion clauses) they should satisfy the requirement that a programmer independent coordinate system can be maintained to describe the process in a helpful and manageable way.
Many C-like programming languages, for example Rust and Java, do have an additional “clause considered as bridling its use,” the break to a label. An even more restricted syntax might be something like break 2 continue; to break out of two levels of the nested loop and resume at the top of the loop containing them. This presents no more of a problem than a C-style break to what Dijkstra wanted to do: defining a concise description of the program state that programmers can keep track of in their heads or a static analyzer would find tractable.
Restricting goto to constructions like this makes it simply a renamed break to a label. The remaining problem with it is that the compiler and the programmer don’t necessarily know you’re only going to use it this way.
If there’s an important post-condition that holds after the loop, and your concern with goto is the same as Dijkstra’s, you might consider stating it in a short comment, something like // We have done foo to every element, or encountered condition and stopped. That would alleviate the problem for humans, and a static analyzer should do fine.
The best solution is to put the loops in a function and then return from that function.
This is essentially the same thing as your goto example, but with the massive benefit that you avoid having yet another goto debate.
Simplified pseudo code:
bool function (void)
{
bool result = something;
for (i = 0; i < N; ++i)
for (j = 0; j < N; j++)
for (k = 0; k < N; ++k)
if (condition)
return something_else;
...
return result;
}
Another benefit here is that you can upgrade from bool to an enum if you come across more than 2 scenarios. You can't really do that with goto in a readable way. The moment you start to use multiple gotos and multiple labels, is the moment you embrace spaghetti coding. Yes, even if you just branch downwards - it will not be pretty to read and maintain.
Notably, if you have 3 nested for loops, that may be an indication that you should try to split your code up in several functions and then this whole discussion might not even be relevant.

Overlapping multidimensional array corruption [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a very insidious issue with two dynamically allocated and reallocated multidimensional arrays, defined as follows:
int *pRawVals[20][181];
and
int *pMaxPlaneRawPlanes[20][46];
These are allocated in a single function: (code condensed for clarity)
...
// iNlat and iNVer bounds checked and OK
for (int lat = 0; lat < iNlat; lat++)
{
pData->pBlendedRawPlanes[lat] = new long long[1 * (iNver + 1)];
for (int sensor = 0; sensor < 20; sensor++)
{
pData->pRawVals[sensor][lat] = new int[1 * (iNver + 1)];
for (int vert = 0; vert <= iNver; vert++)
{
pData->pRawVals[sensor][lat][vert] = SENSOR_UNREAD;
} // end for
} // end for
} // end for
...
for (int sensor = 0; sensor < 20; sensor++)
{
delete[] pData->strayVals[sensor];
pData->strayVals[sensor] = new int[1 * (iNver + 1)];
for (int vert = 0; vert < iNver + 1; vert++)
{
pData->strayVals[sensor][vert] = SENSOR_UNREAD;
} // end for
for (int lat = 0; lat < 46; lat++)
{
pData->pMaxPlaneRawPlanes[sensor][lat] = new int[361];
// for (int iFillMem = 0; iFillMem < 361; iFillMem++)
for (int vert = 0; vert < iNver; vert++)
{
pData->pMaxPlaneRawPlanes[sensor][lat][vert] = SENSOR_UNREAD;
} // end for
} // end for
} // end for
... and deallocated in another function:
for (int lat = 0; lat < pData->iNUserLats; lat++) // iNUserLats <= 181
{
for (int sensor = 0; sensor < 20; sensor++)
{
if (pData->pRawVals[sensor][lat] != NULL)
{
delete[] pData->pRawVals[sensor][lat];
pData->pRawVals[sensor][lat] = NULL;
} // end if
} // end for
}
...
for (int sensor = 0; sensor < 20; sensor++)
{
for (int lat = 0; lat < 46; lat++)
{
if (pData->pMaxPlaneRawPlanes[sensor][lat] != NULL)
{
delete[] pData->pMaxPlaneRawPlanes[sensor][lat];
pData->pMaxPlaneRawPlanes[sensor][lat] = NULL;
} // end if
} // end for
} // end for
Hope I got enough of the code posted. At any rate, when deallocating pMaxPlaneRawPlanes on a second pass through the code, it turns out that certain elements of that array overlap elements of pRawVals and the deallocation causes a crash - appears that those locations may have been freed previously but I can't seem to point the finger at exactly how it's happening.
Any hints on how to narrow that kind of thing down? I run development on Windows 7 Ultimate 64 bit, but the app is compiled for 32 bit.
Thanks
You may go out of range in any of your array, or you may go out of range elsewhere.
If you are using Visual Studio 2019, or you are using gcc or clang, you can give ASan (Address Sanitizer) a try. (VS2019 link)
Otherwise you can try Application Verifier with Full Heap check enabled.
It is also possible to use custom allocation and allocate memory the way that it will access violation on out of bounds, even if off by one. It is essentially duplicating Application Verifier for particular allocations.
Using std::array or std::vector recommended in comments will also help making fewer errors that lead to heap corruption in the first place. vector manages deallocations automatically, and also in debug builds may have checks for out-of-range errors.

Local variable resets when I'm using the debugger C++

I'm using the debugger to check if my programm works but I'm getting a segfault on a precise line. when I'm checking what's wrong, a local variable says <no such value>. What's happening? I've checked its value for each k and it's working until k=36. Do you think that local variables are reseted if I'm using it in a too long loop? I remember that I've used it in a loop where k=41 and it was working very well.
Variables of my class:
masseVolumique= 7850;
dExterieur= 0.1778;
epaisseur= 0.019;
masseFlotteur1 = 526;
masseFlotteur2 = 94;
largeurFlotteur1 = 1.35+2;
largeurFlotteur2 = 0.83+2;
rayonBends = 0.699;
precision = 2;
All the other variables are defined and I can see their value in the debugger mode.
int k=0;
j=0;
double theta=0;
double phi=0;
double offsetDebut;
double offsetFin;
double r=0;
int nbPos = 0;
for(int i=0;i<nbSegments;i++)
{
theta=acos((coordonnees[i+1][0]-coordonnees[i][0])/pow(pow(coordonnees[i+1][0]-coordonnees[i][0],2)+pow(coordonnees[i+1][1]-coordonnees[i][1],2),0.5));
phi=acos((coordonnees[i+1][2]-coordonnees[i][2])/pow(pow(coordonnees[i+1][0]-coordonnees[i][0],2)+pow(coordonnees[i+1][1]-coordonnees[i][1],2)+pow(coordonnees[i+1][2]-coordonnees[i][2],2),0.5));
if(i==0)
{
offsetDebut=3+largeurFlotteur1/2;
}
else
{
offsetDebut=rayonBends+largeurFlotteur1/2;
}
if(i==(nbSegments-1))
{
offsetFin=3+largeurFlotteur1/2;
}
else
{
offsetFin=rayonBends+largeurFlotteur1/2;
}
j=0;
do
{
r=j*precision+offsetDebut; //segfault: precision <no such value>
tabPos[k*5+0]=k;
tabPos[k*5+1]=i+1;
tabPos[k*5+2]=coordonnees[i][0]+r*cos(theta)*sin(phi);
tabPos[k*5+3]=coordonnees[i][1]+r*sin(theta)*sin(phi);
if(r*cos(phi)<0.01)
{
tabPos[k*5+4]=coordonnees[i][2];
}
else
{
tabPos[k*5+4]=coordonnees[i][2]+r*cos(phi);
}
k=k+1;
j=j+1;
}
while (r<(segments[i]-offsetFin)) ;
}
Ok the problem came from the calculation of tabPos length. I was calculating a too short length. In the loop, I was trying to access part of tabPos that were not declared.
Actually, I think a lot of segfault problem comes from index problems. I'll look at this very carefully now.

Need to find a logic error in a card shuffling method

I'm trying to write a method that takes an array of integers (0-51, in that order), cuts it into two separate arrays (A and B in the below function by using the cut method, which I know for sure works) and then re-fuses the two arrays together by randomly selecting 0, 1 or 2 cards from the BOTTOM of either A or B and then adding them to the deck.
(ps- by "array" I mean linked list, I just said array because I thought it would be conceptually easier)
This is my code so far, it works, but there's a definite bias when it comes to where the cards land. Can anybody spot my logic error?
[code]
void Deck::shuffle(){
IntList *A = new IntList();
IntList *B = new IntList();
cut(A, B);
IntListNode *aMarker = new IntListNode;
aMarker = A->getSentinel()->next;
//cout<< A->getSentinel()->prev->prev->data <<'\n'<<'\n';
IntListNode *bMarker = new IntListNode;
bMarker = B->getSentinel()->next;
//cout<< B->getSentinel()->prev->data;
deckList.clear();
srand(time(NULL));
int randNum = 0, numCards = 0, totalNumCards = 0;
bool selector = true, aisDone = false, bisDone = false;
while(totalNumCards < 52){
randNum = rand() % 3;
if(randNum == 0){
selector = !selector;
continue;
}
numCards = randNum;
if(!aisDone && !bisDone){
if(selector){
for(int i = 0; i < numCards; i++){
deckList.push_back(aMarker->data);
aMarker = (aMarker->next);
if(aMarker == A->getSentinel()){
aisDone = true;
break;
}
}
selector = false;
}else{
for(int i = 0; i < numCards; i++){
deckList.push_back(bMarker->data);
bMarker = (bMarker->next);
if(bMarker == B->getSentinel()){
bisDone = true;
break;
}
}
selector = true;
}
}
if(aisDone && !bisDone){
for(int i = 0; i < (52 - totalNumCards); i++){
deckList.push_back(bMarker->data);
bMarker = (bMarker->next);
if(bMarker == B->getSentinel()){
bisDone = true;
break;
}
}
//return;
}
if(bisDone && !aisDone){
for(int i = 0; i < (52 - totalNumCards); i++){
deckList.push_back(aMarker->data);
aMarker = (aMarker->next);
if(aMarker == A->getSentinel()){
aisDone = true;
break;
}
}
//return;
}
totalNumCards += numCards;
}
int tempSum = 0;
IntListNode *tempNode = deckList.head();
for(int j = 0; j < 52; j++){
//cout<< (tempNode->data) << '\n';
tempSum += (tempNode->data);
tempNode = (tempNode ->next);
}
if(tempSum != 1326)
system("PAUSE");
return;
}
[/code]
What about just using std::random_shuffle? Yeah, it won't work for linked list, but you can change it to vector :)
If your instructor would have the moral to teach you programming the way it should be done then they'd encourage you to solve the problem like so, with four lines of code:
#include<algorithm>
#include<vector>
// ...
std::vector<int> cards; // fill it in ...
std::random_shuffle(cards.begin(), cards.end());
Using the standard library is the right way of doing things. Writing code on your own when you can solve the problem with the standard library is the wrong way of doing things. Your instructor doesn't teach you right. If they want to get a point across (say, have you practice using pointers) then they should be more attentive in selecting the exercise they give you.
That speech given, here is a solution worse than the above but better than your instructor's:
52 times do the following:
Choose two random none-equal integers in the range [0,52).
Swap the values in the array corresponding to these positions.
For most random number generators, the low bits are the least random ones. So your line
randNum = rand() % 3;
should be modified to get its value more from the high- to middle-order bits from rand.
Your expectations may be off. I notice that you swap the selector if your random value is 0. Coupled with the relative non-randomness of randNum, this may be your problem. Perhaps you need to make things less random to make them appear more random, such as swapping the selector every time through the loop, and always taking 1 or more cards from the selected deck.
Comments:
srand(time(NULL));
This should only be called once during an applications run. This it is usally best to call it in main() as you start.
int randNum = 0, numCards = 0, totalNumCards = 0;
bool selector = true, aisDone = false, bisDone = false;
One identifier per line. Every coding standard written has this rule. It also prevents some subtle errors that can creep in when using pointers. Get used to it.
randNum = rand() % 3;
The bottom bits of rand are the lest random.
rand Num = rand() / (MAX_RAND / 3.0);
Question:
if(!aisDone && !bisDone)
{
This can execute
and set one of the above to isDone
Example:
Exit state aisDone == false bsiDone == false // OK
Exit state aisDone == true bsiDone == false // Will run below
Exit state aisDone == false bsiDone == ture // Will run below
}
if(aisDone && !bisDone)
{
Is this allowed to run if the first block above is run?
}
if(bisDone && !aisDone)
{
Is this allowed to run if the first block above is run?
}
The rest is too complicated and I don't understand.
I can think of simpler techniques to get a good shuffle of a deck of cards:
for(loop = 0 .. 51)
{
rand = rand(51 - loop);
swap(loop, loop+rand);
}
The above simulates picking a card at random from the deck A and putting it on the top of deck B (deck B initially being empty). When the loop completes B is now A (as it was done in place).
Thus each card (from A) has the same probability of being placed at any position in B.