Segmentation Fault in pointers

Viewed 63

I was trying to compare both "arrays" and "pointers as arrays". When I run part1 and part2 separately, they execute fine but when I run the whole code, I get segmentation fault.

#include<stdio.h>

int main(){
    int *p;
    int arr[5],i,var;

    //PART-1
    p=&var;
    for(i=0;i<5;i++){
        *(p+i)=i+1;
    }

    printf("\n\nPointers: ");
    for(i=0;i<5;i++){
        printf("%d ",*(p+i));
    }

    //PART-2
    for(i=0;i<5;i++){
        arr[i]=i+1;
    }

    printf("Array: ");
    for(i=0;i<5;i++){
        printf("%d ",arr[i]);
    }

    return 0;
}

This code runs fine:

#include <stdio.h>

int main()
{
    int *p;
    int arr[5],i,var;

    p=&var;
    for(i=0;i<5;i++){
        *(p+i)=i+1;
    }

    printf("\n\nPointers: ");
    for(i=0;i<5;i++){
        printf("%d ",*(p+i));
    }

    return 0;
}
2 Answers

Your code invokes undefined behaviour:

p=&var;
for(i=0;i<5;i++){
    *(p+i)=i+1;

Your pointer points to the address of a single integer variable. It is not allowed to access any memory beyond that.

Whatever happens to be located at *(p+i) is not allowed to be accessed. Additionally it is not initialized as a pointer and dereferencing it is another source of undefined behaviour. Both accesses can cause your segementation fault.

As with all UB, it may crash immediately or not. This is why runnign both parts crashes while they seemingly work separately.

From your code

  int arr[5],i,var;

var is not an array so, this code access non initialized memory it is undefined Behavior

p=&var;
for(i=0;i<5;i++){
    *(p+i)=i+1;
}

printf("\n\nPointers: ");
for(i=0;i<5;i++){
    printf("%d ",*(p+i));
}

So change var definition to var[5]

Related