ChiselD ChiselD - 1 month ago 18
C Question

Abort trap: 6 error when working with array in C

I am a beginner to C and am trying to get more familiar with arrays and the concept of manual memory allocation by doing simple exercises. I have been reading all the (many) questions on SO regarding the "Abort trap: 6" error, and though I've learned a lot, they haven't solved my issue.

Similar threads I checked out include:

"Abort trap: 6" running C program on a Mac

"Abort trap: 6" error in C?

...and more, all slightly different than what I'm dealing with.

The problem seems to be that I'm writing to memory I don't have access to, but I thought that by making the array big enough when I declare it, I would avoid this issue. Evidently I was wrong!

The code is supposed to simply create an array that holds 100 ints (in positions 0 to 99), and assign each one the value of its position (i.e. the first item in the array should be the int 0, and the last should be the int 99). When I run this code, I get all the example printf statements as expected – with the correct values in them – but it's followed by a line saying "Abort trap: 6".

Could someone take a look at my code and tell me what I'm doing wrong to cause this error?

#include <stdio.h>


int main(void)
{
int obvs[101];

for (int i = 0; i < sizeof(obvs); i++)
{
obvs[i] = i;
}

printf("obvs[9] = %i\n", obvs[9]);
printf("obvs[13] = %i\n", obvs[13]);
printf("obvs[37] = %i\n", obvs[37]);
printf("obvs[74] = %i\n", obvs[74]);
printf("obvs[99] = %i\n", obvs[99]);

return 0;
}

Answer Source

Your problem is your for loop:

for (int i = 0; i < sizeof(obvs); i++)

More specifically, your porblem is your terminating condition:

i < sizeof(obvs)

As your code is written, sizeof(obvs) is going to return the size of the memory allocated (in this case, 404 bytes since an int requires 4 bytes of memory) to your array not the size of your array, 101, like you're probably expecting.

Change your for loop to read:

for (int i = 0; i < 101); i++)

or

for (int i = 0; i < (sizeof(obvs) / sizeof(int)); i++)

And it should fix your problem. A good habit to get into is to store constant values in macros so that you're guaranteed to use the same value each time it's used (and save yourself some headache).

So you could rewrite your code to read:

#include <stdio.h>

#define ARRAY_SIZE 101

int main(void)
{
    int obvs[ARRAY_SIZE];

    for (int i = 0; i < ARRAY_SIZE; i++)
    {
        obvs[i] = i;
    }

    printf("obvs[9] = %i\n", obvs[9]);
    printf("obvs[13] = %i\n", obvs[13]);
    printf("obvs[37] = %i\n", obvs[37]);
    printf("obvs[74] = %i\n", obvs[74]);
    printf("obvs[99] = %i\n", obvs[99]);

    return 0;
}