Percy
Percy

Reputation: 109

Segmentation fault (core dumped)

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]);
}

Upvotes: 8

Views: 33252

Answers (2)

Michael Dillon
Michael Dillon

Reputation: 32392

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.

Upvotes: 5

Jesus Ramos
Jesus Ramos

Reputation: 23266

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.

Upvotes: 10

Related Questions