miller
miller

Reputation: 1728

Segmentation fault on main

I have small C program. When I compile it with gcc, everything works fine, but when I try to run it I get this message:

Segmentation fault (core dumped)

I tried to debug it with gdb andwhen I place a breakpoint on main() and start the program, I get this message in gdb:

Single stepping until exit from function main, which has no line number information.

Program received signal SIGSEGV, Segmentation fault.

0x00007ffff7a56ad4 in ?? () from /lib/x86_64-linux-gnu/libc.so.6

And this is the very beginning of mine mani() function:

int main(int argc, char **argv) {

   long N;
   double *A, *B, *C, t;

   srand(time(NULL));

   N = atoi(argv[1]);
   A = (double *) malloc(N * N * sizeof(double));
   B = (double *) malloc(N * N * sizeof(double));
   C = (double *) malloc(N * N * sizeof(double));
   matFillSimple(N, A, 1.0);
   matFillSimple(N, B, 2.0);
   matFillSimple(N, C, 0.0);
...

Upvotes: 1

Views: 3086

Answers (1)

Alex Reynolds
Alex Reynolds

Reputation: 96937

You should check that the type of N matches the return value of atoi(). Avoid relying on implicit type conversions as this can lead to problems where a value gets turned into something you weren't expecting.

If you compile with all warnings (gcc -Wall) then you should probably see a warning to this effect. There are other warnings you can turn on with GCC, listed in the documentation. Compiling with warnings a good habit to get into.

Further, get into the (good) habit of error checking when handling pointers. Be sure to check if you allocate memory successfully after each call.

In other words:

A = (double *) malloc(N * N * sizeof(double));
...

should be something like:

double *A = NULL;
A = malloc(N * N * sizeof(double));
if (!A) {
    fprintf(stderr, "ERROR: Could not allocate space for A\n");
    return EXIT_FAILURE;
}
...

Repeat for each of your double pointers.

My suspicion is that your value of N is so large (and N * N even larger) that your system runs out of memory before you can run matFillSimple(). This should help troubleshoot that possibility.

Upvotes: 2

Related Questions