8
votes

I am relatively new on C, I am trying to run a simple program and I get this Error message: Segmentation fault (core dumped) I just want to print any value of the array bits but I can not, I'd appreciate any help on this error.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <malloc.h>

int main()
{
    const long int N = 1000000000;
    const int smallN = 125000000;
    char bits[smallN];

    for(int i=0; i<smallN; i++){
        bits[i]=0xff;
    }

    printf("character = %c \n", bits[5]);
}
2

2 Answers

10
votes

The array seems to be exceeding the stack size (bits is an array on the stack). You can either try making it global or allocating the array using malloc.

5
votes

Note that this is the kind of thing that Valgrind is good at pinpointing for you. If you had done this inside a large chunk of code, Valgrind would point you to the line that was wrong.

For learning C in this day and age, Valgrind it indispensable.