fsyscall
fsyscall

Reputation: 51

Segmentation error that occurs when there is no initialized variable defined

I am working with pointers in C. I encountered a problem while dealing with the pointers.

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

int main(){
  int x = 1, y = 2, z[10];
  int *ip;  
  
  printf("initial value of x:%d\n",x);
  printf("initial value of y:%d\n",y);
  printf("inital value of ip: %d\n",*ip);
    
  return 0;
}

This program works properly. But in the program below,Segmentation fault occurs when there is no initialized variable defined.

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

int main(){
  int x = 1, y = 2;
  int *ip;  
  
  printf("initial value of x:%d\n",x);
  printf("initial value of y:%d\n",y);
  printf("inital value of ip: %d\n",*ip);
    
  return 0;
}

Why does this error occur? What is the relationship between segmentation error and variable definition?

Upvotes: 1

Views: 49

Answers (1)

Acorn
Acorn

Reputation: 26066

Why does this error occur?

Both programs contain undefined behavior, so the expectation is that both of them do not work.

The issue is that you are dereferencing an uninitialized pointer:

int *ip; // uninitialized, may contain any value

// ...

printf("...", *ip);
           // ^^^ dereference

That dereference may give you apparently random data, a constant value or give a segmentation fault.

What exactly happens depends on your compiler, your architecture, your operating system, the optimization flags and other details.

What is the relationship between segmentation error and variable definition?

There is no relationship. The definition of z here is making your first program "seem to work" by chance. As soon as you change something else (like updating your compiler to a new version), it may stop "working" again.

Upvotes: 1

Related Questions