Search code examples
c++debuggingcompilationgarbage

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;
}

Solution

  • For one thing, this:

        //save entire array in prev
        prevrow = new int [i+1];
        prevrow = currow;
    

    copies the pointer, not the whole array.