Search code examples
cpointerssegmentation-faultcoredump

got segmentation error (core dumped) doing pointer operations


I got a segmentation error (core dumped) when trying to run the program. It's just some simple pointer operations, but I can't figure out the problem.

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;
}

Solution

  • 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.