0

I am getting segmentation faults when using malloc to allocate 16777216 (16mb) and trying to iterate over that array n times.. I can't seem to find why I am getting segmentation faults..

register *a;
a = malloc(16777216);
int times, i, dummy, timeTaken;
for (times = 0; times < 10000; times++) {
    for (i = 0; i < 16777216; i += 1) {
        dummy = a[i];
    }
}
Dante May Code
  • 11,177
  • 9
  • 49
  • 81
  • 2
    What are you expecting `register *a;` to do? Also, you need to check that `malloc` didn't return `NULL`. – David Schwartz Dec 12 '12 at 03:42
  • it should act as an array of 16mb holding 4 million ints.. – user1893417 Dec 12 '12 at 03:43
  • BTW--as a matter of good style don't use the type defaults to `int` behavior of c. Just don't. – dmckee --- ex-moderator kitten Dec 12 '12 at 03:46
  • You can't access the 16th million element of an array of 4 million `int` values. – Jonathan Leffler Dec 12 '12 at 03:50
  • `register *a` is a really old declaration equivalent to `register int *a`. A minor variation on this question was asked yesterday — the antiquated declaration of `a` and the array size are giveaways. Roughly the same as [Having trouble finding the length of an array in C](http://stackoverflow.com/questions/13813246/having-trouble-finding-the-length-of-an-array-in-c). The same basic misconceptions are on display. – Jonathan Leffler Dec 12 '12 at 03:52

1 Answers1

2

It should be:

 register int *a;
 a = malloc(16777216*sizeof(int));
Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51
  • To explain this a bit more: You're assuming you're accessing one byte at a time. But since `a` is a `register`, its size is implementation-defined, and most likely not 1 byte, but 4. I'd say this answer is close, but you'd want `sizeof(register)` instead of `sizeof(int)` – Moshe Dec 12 '12 at 03:48
  • my assignment says register* a and a=sbrk(4*1024*4096+8192); – user1893417 Dec 12 '12 at 03:48
  • This will work perfectly (you justtt beat to an answer!), but judging by OP's comment "it should act as an array of 16mb holding 4 million ints..", his `malloc` was correct, but the for loop should've been until 16777216/sizeof(int) – username tbd Dec 12 '12 at 03:48
  • 1
    No, Moshe; `register *a;` is an archaic way of writing `register int *a;` that was disapproved of in C89 and outlawed in C99 (but is still recognized by compilers). – Jonathan Leffler Dec 12 '12 at 03:49
  • so I should make by array length = 16777216/sizeof(int) – user1893417 Dec 12 '12 at 03:55
  • @user1893417: The upper bound on your inner loop, indexed by `i`, should be `16777216/sizeof(int)` (which is a compile time constant). You didn't allocate 16 million integers; you shouldn't try accessing 16 million integers. You did allocate 16 million bytes, which gives you 4 million 4-byte integers. (Speaking loosely: 16 MiB was allocated; I guess that means you have 4 mebi-ints.) – Jonathan Leffler Dec 12 '12 at 16:35