0

I got segmentation error(core dumped) when trying to running the program. It's just some simple pointer operations, but I can't figure out the problem. Please help me out. Thanks in advance!

int get_address_value(int* ptr) {
  return *ptr;
}

void put_value_to_address(int val, int* ptr) {
  *ptr = val;
}


int main(int argc, char* argv[]) {  
  int* ptr;
  put_value_to_address(400, ptr);
  printf("value in address is %d\n", get_address_value(ptr));

  return 0;
}
Shen
  • 2,911
  • 3
  • 15
  • 10
  • Where is `ptr` defined? – TheQAGuy Nov 09 '15 at 01:48
  • @JackWilliams I forget to define the ptr when editing the post. I did define it in the program. Sorry about the confusing. – Shen Nov 09 '15 at 01:55
  • So the answers are correct but also you should enable compiler warnings because when i ran this my compiler gave me a warning telling me ptr was being used uninitialized in main() – TheQAGuy Nov 09 '15 at 02:03

2 Answers2

3

You have an uninitialized pointer. Accessing that pointer causes undefined behavior. In your case, the undefined behavior manifests as segmentation fault/error.

You need to make sure that ptr points to something valid before changing the value of what it points to in put_value_to_address.

int* ptr = malloc(sizeof(int));

or

int i;
int* ptr = &i;

If you use malloc, make sure to deallocate the memory. Add

free(ptr);

before the end of main.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

The pointer ptr is uninitialized, to it contains a garbage value. That means that it points to arbitrary memory address, which you might not be able to write to. That is what is causing the Segmentation Fault.

Arthur Laks
  • 524
  • 4
  • 8