Ginko
Ginko

Reputation: 395

Printing text causes memory issue

I am doing a program to solve matrixes and when I was trying to debug I wrote code like that:

double* row = matrix[i];
int first_nz = get_first_nz_el_idx(row, size);
cout << row[first_nz];

And the funny thing is, when I put that cout instruction there, my results completly change, it starts to return random, big numbers, like 01.55e+2311. When I delete that cout instruction, results are correct. I could work-around that problem somehow, but I want to know what's the reason of this behavior. Also, when I do 'cout << "anything"; it's the same issue. But when I call other function like pow(3, 2) - its nothing wrong.

There is the function, which sums some elements in a row passed:

double sum_nz_el(double* row, int size)
{
    int first = get_first_nz_el_idx(row, size) + 1;
    int last = size - 1;
    double sum;
    if (first > size - 2)
        return 0;
    while (first < last)
    {
        sum += row[first];
        first++;
    }
    return sum;
}

int get_first_nz_el_idx(double* row, int size)
{
    int i = size - 2;
    while (!(row[i - 1] == 0 || i == 0))
        i--;
    return i;
}

And when I do cout << row[first_nz] or cout << sum_nz_el(row, size) (it doesn't really matter which one, problem appears in both cases), the function sum_nz_el starts to return random, big numbers, when that row is passed. It should be like max 2,5

Row could be like that: 0 0 0 23 41 11

Upvotes: 1

Views: 54

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35454

The issue is this line:

double sum;

This variable is local, thus uninitialized. It starts out with a garbage value. That garbage value can be anything, including 0. Also, you can't predict what the garbage value may be, or even "control it" by removing or adding irrelevant lines of code (like the cout statement you mentioned).

To fix this issue, all you need is to simply initialize the variable:

double sum = 0.0;

Also, you don't need that loop if you used the algorithm function std::accumulate:

#include <numeric>
//..
double sum_nz_el(double* row, int size)
{
    int first = get_first_nz_el_idx(row, size) + 1;
    int last = size - 1;
    if (first > size - 2)
       return 0;
    return std::accumulate(row + first, row + last, 0.0);
}

Upvotes: 2

Related Questions