3

The following program produces a segmentation fault, and I'm not sure why. malloc succeeds, so it doesn't seem to be an initialisation error, but for some reason, it segfaults when I access the 253900th element. The array is only 4 * 1e6 bytes, or a about a Megabyte.

This does produce a lot of output

#include <stdlib.h> #include <stdio.h> int *long_array(size_t N) { int *arr = (int *) malloc(N); if (arr == NULL) { printf("could not malloc"); exit(1); } for (size_t i = 0; i < N; i++) { printf(".. %ld ", i); arr[i] = 10; } printf("done with loop\n"); return arr; } int main(void) { int *arr = long_array(1000000); printf("%d", arr[5050]); return 0; } 

I compile this with gcc -std=c99 and run the output to see the final few numbers printed before the segfault:

253899 .. 253900 .. 2 segmentation fault (core dumped) ./a.out 

I don't understand why accessing a particular index is causing the segmentation fault. I can guess that I must be accessing a memory location outside of my processes address space, but this seems like a bug if I successfully allocated the memory from within my address space.

1
  • 2
    Your array is 1Mb roughly, but you're trying to access elements beyond that. When allocating, you're not taking into account the size of int. Use int *arr = malloc(N*sizeof(*arr)); Commented Feb 2, 2014 at 16:14

3 Answers 3

6

malloc(sizeof(int)*N) instead of malloc(N). Otherwise you'd get an array of N bytes, not N integers.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh jeez, I just read about that. Sorry, brain farts. Thanks for pointing it out!
0

use

 int *arr = (int *) malloc(N * sizeof(int)); 

Comments

0

Your code is correct but the problem here is that your did not consider the size of an integer while allocating memory. You just allocated :

int *arr=(int *)malloc(N); 

here you just allocated size of N but you have to consider size of integer in your machine. If you allocate just 10000000 size of memory and sizeof(int) in you machine is 4 then it can just access (10000000/4) memory ......... So you have to allocate memory like:

int *arr=(int *)malloc(N*sizeof(int)) 

or

int *arr=(int *)malloc(N*sizeof(*arr)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.