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
First:
You have a stack overflow.
Assuming
doubleis8bytes 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
Nto10(so it does no longer segfault) and add this function call at the beginning of your program:You’ll see that the stack size is different in the shell (for example the printed value of
systemis8192) than in the Makefile context (for example the printed value ofsystemisunlimited).