Dave
Dave

Reputation: 19

Why is this Segfault Occuring?

So I've traced the segfault to the line, but I don't understand why this is a segfault. Can someone elaborate on the error of my ways?

Here are the variable declarations.

size_t i, j, n, m, chunk_size, pixel_size;
i = j = n = m = 0;
chunk_size = 256;
pixel_size = 4;

Here are the array declarations.

uint8_t** values = new uint8_t*[chunk_size];
for (i = 0; i < chunk_size; ++ i)
    values[i] = new uint8_t[chunk_size];

float** a1 = new float*[chunk_size];
for (i = 0; i < chunk_size; ++i)
    a1[i] = new float[chunk_size];

And here is where the segfault occurs.

float delta, d;

for (i = 0; i < 256; ++i) {
    for (j = n = m = d = 0; j < 256; j = m) {
        while (i == 0 || d != 0) {
            d = a1[i][m];    <------SEGFAULT per GDB
            ++m;
        }
        delta = (d - a1[i][j]) / m;
        n = j + 1;
        while (n < j + m) {
            a1[i][n] = a1[i][n - 1] + delta;
            ++n;
        }
    }
}

I'm fairly new to C++ and can't figure out why this would be a segfault. Is this not the proper way to set a variables value to a variable in an array? Is that the source of my segfault?

Note: The point of this whole thing is too expand a 4x4 array to a 256x256 array with my simpleton interpolation formula.

Upvotes: 1

Views: 135

Answers (3)

Corb3nik
Corb3nik

Reputation: 1177

The problem is in the following lines :

while (i == 0 || d != 0) {
        d = a1[i][m];    <------SEGFAULT per GDB
        ++m;
}

Your while loop will keep on going while i equals 0. Since you never increment i in your while loop, m keeps on incrementing forever until arriving out of bounds, causing the segfault issue that you are having.

Make sure you check the values of i and m, so that they are in the allocated memory range and your code will work.

Upvotes: 1

James Adkison
James Adkison

Reputation: 9602

Your outer loop starts out with i = 0 and the inner loops starts with d = 0 and the logic controlling the while loop is not sufficient (see code comment).

for (i = 0; i < 256; ++i) {
    for (j = n = m = d = 0; j < 256; j = m) {
        // Here i == 0 is ALWAYS true (so d != 0 is ignored due to
        // short-circuit evaluation) and then 'm' is continuously incremented
        // until it goes out of bounds
        while (i == 0 || d != 0) {
        d = a1[i][m];    <------SEGFAULT per GDB
        ++m;
    }
    delta = (d - a1[i][j]) / m;
    n = j + 1;
    while (n < j + m) {
        a1[i][n] = a1[i][n - 1] + delta;
        ++n;
    }
}

Upvotes: 1

st.eve
st.eve

Reputation: 114

while (i == 0 || d != 0) {
    d = a1[i][m];    <------SEGFAULT per GDB
    ++m;
}

This is an endless while loop, in some cases (e.g. in the first iteration of the outer loop).

Upvotes: 1

Related Questions