1

I'm a real C++ noob, so bear with me.

I have a simple program. When I compile it with g++ -Wall prog.cpp -o prog and then run it with ./prog it just segfaults.

After some tinkering I wrote a makefile (see below). If I run make test, the program compiles and runs fine. If I run it with ./prog, it segfaults. (The exact error message is Segmentation fault (core dumped))

Can anyone explain why?

Here is the program:

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>

int main() {

    srand(time(NULL));

    //int i, j, k, i2, j2, k2;
    int N = 1000;

    double mul1[N][N];
    double mul2[N][N];
    double res[N][N];

    printf("N: %d\n", N);

    for(int x=0; x<N; x++) {
        for(int y=0; y<N; y++) {
            mul1[x][y] = rand() % 100;
            mul2[x][y] = rand() % 100;
            res[x][y] = 0;
        }
    }

    return 0;
}

Here is the makefile:

all: prog

prog: prog.cpp
    $(CXX) -Wall -g -o $@ prog.cpp

test: prog
    ./prog

clean: 
    rm -f prog
Wukerplank
  • 4,156
  • 2
  • 28
  • 45

1 Answers1

4

First:

int N = 1000;

double mul1[N][N];
double mul2[N][N];
double res[N][N];

You have a stack overflow.

Assuming double is 8 bytes on your platform, your 3 arrays are more than 20 MB (3 * 8 * 1000 * 1000) in size. For example on my Linux machine the stack size allocated for every process is 8192 kB.

Second:

Regarding why it does not work on the shell but it works in the Makefile context you can try this:

Change N to 10 (so it does no longer segfault) and add this function call at the beginning of your program:

 system("ulimit -s");  // system is in stdlib.h

You'll see that the stack size is different in the shell (for example the printed value of system is 8192) than in the Makefile context (for example the printed value of system is unlimited).

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Please bear with me: My machine has 2GB RAM, how is this a problem? And why does it work with `make test`? Thanks! – Wukerplank Nov 20 '12 at 22:01
  • You have 2GB of *physical* memory. The stack overflow issue has to do with virtual memory and address space. It has nothing whatsoever to do with use of physical memory. – David Schwartz Nov 20 '12 at 22:02
  • @Wukerplank this is not a question of RAM you have but of how much the OS allocates for each process. In Linux use `ulimit -s` to know how much. – ouah Nov 20 '12 at 22:02
  • Ok, got it. My stack size is 8192 kB as well. Still the `make test` thing that bugs me... – Wukerplank Nov 20 '12 at 22:03
  • @Wukerplank are you sure the program is executed? Add a `printf` before the `return 0;` statement to ensure. – ouah Nov 20 '12 at 22:06
  • @ouah Thanks for the update on the Makefile context! Consider my mind blown. – Wukerplank Nov 20 '12 at 22:42