0

I'm having some problems with the following code. newrows is a parameter which is directly given to the function I'm working in. elements is being calculated a bit earlier using another parameter. Somehow, for some combinations of values for newrows and elements I'm getting a core dump while other combinations work fine. Usually, when the core dump occurs there have been 20000 to 25000 iterations. However, when everything works fine there have been up to 40000 iterations.

int32_t newimage[newrows][elements][3];
    int32_t pixelcounter[newrows][elements];

    //int32_t norm, angle, rohmax;
    //double r, alpha, beta, m, mu;



    //initialize arrays

    for(i=0; i<newrows; i++){
        for(j=0; j<elements; j++){
            pixelcounter[i][j] = 0;
            newimage[i][j][0] = 0;
            newimage[i][j][1] = 0;
            newimage[i][j][2] = 0;

        }
    }

combination that works fine: 200 : 188

combination that leads to core dump: 200 : 376

I am using linux btw :-)

1 Answers1

0

This is most likely a stack space issue. Note that newimage and pixelcounter are being allocated in the stack frame of whatever function these are being declared in. You can quickly run out of space trying to allocate large amount of data. Your 3d array newimage grows as

#bytes = newrows * elemets * 3

I cleaned up your program (a good piece of advice is to try and present programs that compile, so can people can help you quicker!):

#include <stdio.h>
#include <stdint.h>

void test(size_t newrows, size_t elements) {
    int32_t newimage[newrows][elements][3];
    int32_t pixelcounter[newrows][elements];

    //initialize arrays

    for(size_t i=0; i<newrows; i++) {
        for(size_t j=0; j<elements; j++) {
            pixelcounter[i][j] = 0;
            newimage[i][j][0] = 0;
            newimage[i][j][1] = 0;
            newimage[i][j][2] = 0;
        }
    }
}

int main(void) {
    printf("Size of integer = %ld\n", sizeof(int));
    for (size_t i = 700; ; i += 10) {
            printf("Testing (%ld, %ld)\n", i, i);
            test(i, i);
    }
    return 0;
}

And running this, I see:

Size of integer = 4
Testing (700, 700)
Testing (710, 710)
Testing (720, 720)
Testing (730, 730)
[3]    13482 segmentation fault (core dumped)  ./a.out

So somewhere between 720^2 * 3 * 4 and 730^2 * 3 * 4 bytes, which is about 6 MiB on my 64-bit Linux computer, it might be different on your computer.

The solution in this case is allocate your arrays on the heap, where you will have a lot more memory to work with. More information about heap-allocating multidimensional arrays can be found in How does C allocate space for a 2D (3D...) array when using malloc?.

Community
  • 1
  • 1
Charles
  • 953
  • 1
  • 8
  • 19