user11683992
user11683992

Reputation:

c programming encounters Segmentation fault (core dumped)

I am trying to allocate a big block of memory.

I ran this code firt,

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

int main()
{
    long i;
    long n = 50000;
    printf("trying to malloc %ld memory. ", n);
    long *ptr;
    ptr = (long*) malloc(n * sizeof(int));
    if(ptr == NULL)
    {
        printf("Error! memory not allocated.");
        exit(0);
    }
    for(i = 0; i < n; ++i)
    {
        *(ptr+2*i) = 9;
    }
    for(i = 0; i < 5; ++i)
    {
        printf("%ld ", *(ptr+2*i)); 
    }
    return 0;
}

and then I got this error

Segmentation fault (core dumped)

I know this "you are accessing memory that does not belong to you.", but why

PS:

long n = 5000; works well

Upvotes: 1

Views: 65

Answers (1)

Kevin Montambault
Kevin Montambault

Reputation: 618

When you have a pointer to a datatype, adding 1 to that pointer will actually offset the address by however large the datatype is. If I have a pointer to an integer array at 0x0000, doing myArray += 1; will result in my pointer having the value of 0x0004 (assuming an integer is 4 bytes on my system)

Knowing this, you can see how the line *(ptr+2*i) will go out of the bounds of your array for all values of i greater than i/2

Normally, since you are dynamically creating this array, writing to these addresses would just corrupt heap memory and not cause a segfault. The problem is that your program is going so far out of bounds, it is past the heap and going into memory that doesn't belong to your program. This is why it segfaults for 50000 and not 5000.

Upvotes: 3

Related Questions