Display element in CStringArray on Debugger one bye one? - c++

This code every time display Cat in debugger. First time and second time. But I want to display Cat at 1st time in debugger and then Dog in 2nd time debugger.
int main(){
CStringArray arr;
arr.Add("Cat");
arr.Add("Dog");
for (int i = 0; i < arr.GetSize(); i++)
{
cout<<"arr[i]"<<endl;
}
return 0;*
}
Forget about cout I just used debugger.

Use
for (int i = 0; i < arr.Count(); i++)
{
cout<<arr.GatAt(i)<<endl;
}
cout<<"arr[i]"<<endl; //this will print normal string i.e arr[i]

This is a simple code, it prints Cat and Dog. It won't print Cat, Cat, unless you have an error elsewhere. Are you looking for TRACE or OutputDebugString?
CStringArray arr;
arr.Add("Cat");
arr.Add("Dog");
for (int i = 0; i < arr.GetSize(); i++)
{
const char *temp = arr[i];
TRACE("%s\n", arr[i]);//add break point here to look at temp
//or
//OutputDebugString(arr[i]);
//OutputDebugString("\n");
}
ps, I think you want to use breakpoints and look at arr[i] on the fly. You can use const char *temp = arr[i] it will make the nth element visible. Otherwise I don't know.
pss, debug feature Autos may not show the value at temp depending on where you put breakpoint, because it makes decisions automatically. But you should be able to look at it by just moving the mouse over to temp.

You can't do it in Autos or Locals views, but you can do it in Watch view. Add to Watch view arr.m_pData,3. Value 2 would be enough here, but let's see what happens if you put a larger number. When you expand the name in the Watch view you will be able to see three items. First two will be Cat and Dog and the third will most likely be '<Error reading characters of string.>'.
There is also a way to tell Visual Studio how to display CStringArray variables properly, but you'd have to make some changes, as described in another answer.

Related

My Visual Studio 2012 program works in Debug, release without debug (ctrl + F5) but not release. How do I fix?

As stated above my program works in Debug and Release without debug (ctrl + F5) however does not work in simply Release.
Just to clarify I have already checked to see if I have some uninitialized variables and I haven't (to the best of my knowledge anyway but I have spent quite some time looking).
I believe to have localized the issue and what I have come across is, in my opinion, very bizarre. First I set up the break points as shown in the picture below:
Then I run the program in release. And instantly the top break point moves:
I found this extremely odd. Now note the number 6302 assigned to 'n'. This number is correct and what I hoped to pass through. Now watch as I continue through the program.
We are still in good shape but then it turns for the worst.
'n' changes to 1178521344, which messes up the rest of my code.
Would someone be able to shed some light on the situation, and even better, offer a solution.
Thanks,
Kevin
Here is the rest of the function if it helps:
NofArr = n;
const int NA = n;
const int NAless = n-1;
double k_0 = (2*PI) / wavelength;
double *E = new double[NAless]; // array to hold the off-diagonal entries
double *D = new double[NA]; // array to hold the diagonal entries on input and eigenvalues on output
int sizeofeach = 0;
trisolver Eigen;
int* start; int* end;
vector< vector<complex <double>> > thebreakup = BreakUp(refidx, posandwidth, start, end);
for(int j = 0; j < (int)thebreakup.size(); j++){
// load the diagonal entries to D
for(int i =0; i < (int)thebreakup[j].size(); i++){
D[i] = -((double)2.0/(dx*dx)) + (k_0*k_0*thebreakup[j][i].real()*thebreakup[j][i].real());
}
// load the off diagonal
for(int i = 0; i < (int)thebreakup[j].size(); i++){
E[i] = (double)1.0 / (dx*dx);
}
sizeofeach = (int)thebreakup[j].size();
double *arr1= new double[sizeofeach];
arr1 = Eigen.EigenSolve(E, D, sizeofeach, mode);
complex <double> tmp( PhaseAndAmp[j][1]*cos(PhaseAndAmp[j][0]), PhaseAndAmp[j][1]*sin(PhaseAndAmp[j][0]));
// rebuild the break up with the mode
for(int i = 0; i < (int)thebreakup[j].size(); i++){
thebreakup[j][i] = (complex<double>(arr1[i],0.0)) * tmp ;
}
delete []arr1;
}
vector<complex<double>> sol = rebuild(thebreakup, start, end);
delete [] E;
delete [] D;
delete [] start;
delete [] end;
return sol;
I'm writing this as an answer, because it's way harder to write as a comment.
What strikes me immediately is the array "arr1"
First you allocate new memory and store a pointer to it in the variable arr1
double *arr1= new double[sizeofeach];
Then, immediately, you overwrite the address.
arr1 = Eigen.EigenSolve(E, D, sizeofeach, mode);
Later, you delete something. Is it safe?
delete []arr1;
It's not the double array you allocated, but something eigensolve returned. Are you sure you have the right to delete it? Try removing the delete here. Also, fix the memory leak too, by removing allocation in the first line I gave.
What worries me even more is that the "this" pointer changes. There is some nasty problem somewhere. At this point, your program has already been corrupted. Look for the issue somewhere else. Valgrind would be a GREAT tool if you can try to compile under linux.
It seems that there is some sort of code optimization going on in your program. It is not always easy to debug optimized code step-by-step since the optimization may reorder instructions.
I cannot see why the fact that 'n' changes to an apparently uninitialized value would be the root cause of the problem, since 'n' is anyways no longer used in your function. Seems like the memory is simply been released as part of the optimization.
I have discovered my mistake. Earlier in the program I was comparing pointers, not what they were pointing at. A stupid mistake but one I wouldn't have spotted without a long debugging session. My boss explained that the information given at the bottom of Visual Studio whilst in release mode cannot be trusted. So to "debug" I had to use std::cout and check variables that way.
So here is the mistake in the code:
if(start > end){
int tmp = start[i];
start[i] = end[i];
end[i] = tmp;
}
Where start and end were defined earlier as:
int* start = new int[NofStacks];
int* end = new int[NofStacks];
And initialized.
Thanks to all those who helped and I feel I must apologise for the stupid error.
The Fix being:
if(start[i] > end[i]){
int tmp = start[i];
start[i] = end[i];
end[i] = tmp;
}

Strange characters appearing in 2D Char Array

I'm coding a game that utilizes a 'grid', which I have created using a 2 dimensional array of structs, which contain a char value and a boolean value. In my program's .h file, I declare the struct and create the grid.
struct Tile
{
char letter;
bool active;
};
Tile grid [6][5];
In my .cpp file, I initialize the grid so that all values are blank.
for (int i = 0; i < 7; ++i)
{
for (int j = 0; j < 6; ++j)
{
grid[i][j].active == false;
//grid[i][j].letter = '.';
//it always crashes when i try doing the above line
}
}
The function that prints the grid, printGrid, is below
for (int i = 0; i < 7; ++i)
{
for (int j = 0; j < 6; ++j)
{
cout << i;
//the above statement is for debugging purposes so that I can see
//which column easier
std::cout << grid[i][j].letter;
}
std::cout << std::endl;
}
cout << "1 2 3 4 5 6" << endl;
Now, the original goal was to have the default .letter value be '.'. But for some reason, when I tried to do this, there are disastrous results; the screen fills up with characters moving so fast I can't entirely see what they are (I recall some hearts and smiley faces), along with an obnoxious, rapid beeping. So I decided to leave that commented line out.
When I run the program without that line, for some reason, the "grid" always displays characters in certain spots, without any input from the user, or without me having expressly declared any values to that spot. For instance, the spot of the 1st column from the left and the bottom row, always has a character in it (grid[6][5].letter). It changes every time I run the program, and I've seen it range from a heart, to the letter A, to the spanish 'n' (the one with a ~ over it).
I thought to myself, "Hey, since grid[6][5] is the spots that are always buggy, I'll just declare those individual spot's .letter values to be blank (' ')!". That didn't work.
I've got no idea why this one spot is giving me trouble. There were other areas that would have an abnormal character, but I was able to neutralize them by setting their .letter values to blank. If anyone has any idea on how to fix this, pleas
EDIT: The other abnormal characters, which appear at grid[6][0], grid[6][1], grid[6][5], and grid[6][4], all make my program crash at later stages if I set them to blank (' '); however, blanking grid[6][5] is the one that makes it crash at the get go. I tried using a debugger, but it wasn't able to tell me anything helpful.
you're running over the end of your arrays
Tile grid [6][5]; needs to be Tile grid [7][6];
or you need to loop only to i < 6 and j < 5.

Recursive call segmentation fault issue

quick question again.
I'm creating a recursive function that will look for elements in a array of "source" rules and apply those rules to an "target array" of rules if the "source" rule type is the same as the target character. Furthermore the function checks to see if the target character is in an array of symbols or not and adds it if it is not (and throws a few flags on the newly applied rule as well). This is all driven by a recursive call that uses a counter to determine how many iterations have passed and is used to determine the spot in the target array the new rule should be applied, so we don't overwrite.
I've put in a little debugging code to show the results too.
Here's the function itself:
//Recursively tack on any non terminal pointed elements
int recursiveTack(rule * inrule[], char target, rule * targetrule[],
int counter, char symbols[])
{
printf("Got into recursiveTack\n");
printf("target is %c\n", target);
printf("counter is %d", counter);
for (int k = 0; k < sizeof(inrule); k++)
{
if (inrule[k]->type == target)
{
//doublecheck to see if we're trying to overwrite
if (targetrule[counter]->used = true)
{
counter++;
}
targetrule[counter]->head = inrule[k]->head;
targetrule[counter]->type = inrule[k]->type;
targetrule[counter]->used = true;
//Check to see if the elements are new to the symbols table and need to be added
if (!contains(returnGotoChar(targetrule[counter]), symbols))
{
//If not then add the new symbol
addChar(returnGotoChar(targetrule[counter]), symbols);
//Also set the goto status of the rule
targetrule[counter]->needsGoto = true;
//Also set the rule's currentGotoChar
targetrule[counter]->currentGotoChar = returnGotoChar(
targetrule[counter]);
}
counter++;
//recursivly add elements from non terminal nodes
if (isNonTerm(targetrule[counter]))
{
char newTarget = returnGotoChar(targetrule[counter]);
counter = recursiveTack(inrule, newTarget, targetrule, counter,
symbols);
}
}
}
//return how many elements we've added
return counter;
}
Here's the call:
if(isNonTerm(I[i+first][second]))
{
printf("Confirmed non termainal\n");
printf("Second being passed: %d\n", second);
//Adds each nonterminal rule to the rules for the I[i+first] array
second = recursiveTack(I[i], targetSymbol, I[i+first], second, symbols[first]);
}
All the arrays being passed in have been initialized prior to this point.
However, the output I get indicates that the recursion is getting killed somewhere before it gets off the ground.
Output:
Second being passed: 0
Confirmed non termainal
Got into recursiveTack
target is E
Segmentation fault
Any help would be great, I've got the rest of the program available too if needs be it's around 700 lines including comments though. I'm pretty sure this is just another case of missing something simple, but let me know what you think.
for(int k = 0; k < sizeof(inrule); k++)
sizeof(inrule) is going to return the size of a pointer type (4 or 8). Probably not what you want. You need to pass the size of the arrays as parameters as well, if you are going to use these types of structures.
It would be better to use Standard Library containers like std::vector, though.
if(targetrule[counter]->used = true){
counter++;
}
// what is the guarantee that targetrule[counter] is actually valid? could you do a printf debug before and after it?
The biggest thing I see here is:
for(int k = 0; k < sizeof(inrule); k++)
This isn't going to do what you think. inrule is an array of pointers, so sizeof(inrule) is going to be the number of elements * sizeof(rule*). This could very quickly lead to running off the end of your array.
try changing that to:
for (int k = 0; k < sizeof(inrule) / sizeof(rule*); ++k)
Something else you might consider is an fflush(stdout); after your print statements. You're crashing while some output is still buffered so it's likely hiding where your crash is happening.
EDIT:
That won't work. If you had a function that did something like:
int x[10];
for (int i = 0; i < sizeof(x) / sizeof(int); ++i) ...
It would work, but on the other side of the function call, the type degrades to int*, and sizeof(int*) is not the same as sizeof(int[10]). You either need to pass the size, or ... better yet, use vectors instead of arrays.

C++ do while loop

I have a vector holding 10 items (all of the same class for simplicity call it 'a'). What I want to do is to check that 'A' isn't either a) hiding the walls or b) hiding another 'A'. I have a collisions function that does this.
The idea is simply to have this looping class go though and move 'A' to the next position, if that potion is causing a collision then it needs to give itself a new random position on the screen. Because the screen is small, there is a good chance that the element will be put onto of another one (or on top of the wall etc). The logic of the code works well in my head - but debugging the code the object just gets stuck in the loop, and stay in the same position. 'A' is supposed to move about the screen, but it stays still!
When I comment out the Do while loop, and move the 'MoveObject()' Function up the code works perfectly the 'A's are moving about the screen. It is just when I try and add the extra functionality to it is when it doesn't work.
void Board::Loop(void){
//Display the postion of that Element.
for (unsigned int i = 0; i <= 10; ++i){
do {
if (checkCollisions(i)==true){
moveObject(i);
}
else{
objects[i]->ResetPostion();
}
}
while (checkCollisions(i) == false);
objects[i]->SetPosition(objects[i]->getXDir(),objects[i]->getYDir());
}
}
The class below is the collision detection. This I will expand later.
bool Board::checkCollisions(int index){
char boundry = map[objects[index]->getXDir()][objects[index]->getYDir()];
//There has been no collisions - therefore don't change anything
if(boundry == SYMBOL_EMPTY){
return false;
}
else{
return true;
}
}
Any help would be much appreciated. I will buy you a virtual beer :-)
Thanks
Edit:
ResetPostion -> this will give the element A a random position on the screen
moveObject -> this will look at the direction of the object and adjust the x and Y cord's appropriately.
I guess you need: do { ...
... } while (checkCollisions(i));
Also, if you have 10 elements, then i = 0; i < 10; i++
And btw. don't write if (something == true), simply if (something) or if (!something)
for (unsigned int i = 0; i <= 10; ++i){
is wrong because that's a loop for eleven items, use
for (unsigned int i = 0; i < 10; ++i){
instead.
You don't define what 'doesn't work' means, so that's all the help I can give for now.
There seems to be a lot of confusion here over basic language structure and logic flow. Writing a few very simple test apps that exercise different language features will probably help you a lot. (So will a step-thru debugger, if you have one)
do/while() is a fairly advanced feature that some people spend whole careers never using, see: do...while vs while
I recommend getting a solid foundation with while and if/else before even using for. Your first look at do should be when you've just finished a while or for loop and realize you could save a mountain of duplicate initialization code if you just changed the order of execution a bit. (Personally I don't even use do for that any more, I just use an iterator with while(true)/break since it lets me pre and post code all within a single loop)
I think this simplifies what you're trying to accomplish:
void Board::Loop(void) {
//Display the postion of that Element.
for (unsigned int i = 0; i < 10; ++i) {
while(IsGoingToCollide(i)) //check is first, do while doesn't make sense
objects[i]->ResetPosition();
moveObject(i); //same as ->SetPosition(XDir, YDir)?
//either explain difference or remove one or the other
}
}
This function name seems ambiguous to me:
bool Board::checkCollisions(int index) {
I'd recommend changing it to:
// returns true if moving to next position (based on inertia) will
// cause overlap with any other object's or structure's current location
bool Board::IsGoingToCollide(int index) {
In contrast checkCollisions() could also mean:
// returns true if there is no overlap between this object's
// current location and any other object's or structure's current location
bool Board::DidntCollide(int index) {
Final note: Double check that ->ResetPosition() puts things inside the boundaries.

Different outputs after debugging and compiling C++ programs

I'm running CodeBlocks on the MingW compiler in an XP virtual machine. I wrote in some simple code, accessible at cl1p , which answers the algorithm question at CodeChef (Well it only answers it partly, as I have not yet included the loop for multiple test cases.
However, my problem is, that while running it in debug mode, it gives the correct output of 5, for the input:
3
1
2 1
1 2 3
However, when I build and run it, it gives the absurd, huge output 131078, what seems like garbage to me. I do not understand how the hell this is happening, but am guessing it's something to do with the dynamic memory allocation. What's the problem here, and how can I fix it? I even ran it through the online compiler at BotSkool, and it worked fine. After adding the loop for test cases, the code even worked correctly on CodeChef!
#include <iostream>
using namespace std;
int main()
{
// Take In number of rows
int numofrows;
cin >> numofrows;
// Input Only item in first row
int * prevrow;
prevrow = new int[1];
cin >> prevrow[0];
// For every other row
for (int currownum = 1; currownum < numofrows; currownum++)
{
// Declare an array for that row's max values
int * currow;
currow = new int[currownum+1];
int curnum;
cin >> curnum;
// If its the first element, max is prevmax + current input
currow[0] = prevrow[0] + curnum;
// for every element
int i = 1;
for (; i <= currownum; i++)
{
cin >> curnum;
// if its not the first element, check whether prevmax or prev-1max is greater. Add to current input
int max = (prevrow[i] > prevrow[i-1]) ? prevrow[i] : prevrow[i-1];
// save as currmax.
currow[i] = max + curnum;
}
// save entire array in prev
prevrow = new int[i+1];
prevrow = currow;
}
// get highest element of array
int ans = 0;
for (int j=0; j<numofrows; j++)
{
if (prevrow[j] > ans)
{
ans = prevrow[j];
}
}
cout << ans;
}
Run the code through Valgrind on a Linux machine and you'll be amazed at how many places your code is leaking memory.
If you are taking the hard road of managing your memory, do it well and 'delete' all the new-allocated memory before allocating more.
If, on the other hand, you prefer the easy road, use a std::vector and forget about memory management.
For one thing, this:
//save entire array in prev
prevrow = new int [i+1];
prevrow = currow;
copies the pointer, not the whole array.
In your loop, you have this line
int max = (prevrow[i]>prevrow[i-1])?prevrow[i]:prevrow[i-1];
On the first iteration of the main loop, when currownum == 1, the loop containing this line will be entered, as i is initialized to 1. But on the first iteration, prevrow only has one element and this line tries to access prevrow[1]. In a debug build, the memory simply gets initialized to zero, but in a normal build, you get some garbage value that just happened to be in the memory, leading to the result you see.
Pretty much always, when you get garbage values in a normal build, but everything is fine in a debug build, you are accessing some uninitialized memory.
Also, your program is leaking memory like crazy. For instance, you don't need to assign any result of new inside the loop to prevrow because right after that you change prevrow to point to another block of allocated memory. Also, you should call delete for any memory that you are no longer using.