Search code examples
cpointerssegmentation-faultcoredump

Why am I getting segmentation (core dump)?


I did an exercise on youtube and I ended up with the same solution he had but his code was able to get the address of what the pointer is pointing to but when I compiled mine and run it I get an error segmentation fault (core dump), am I somehow accessing memory that I am not supposed to access? How is it that his code was able to run but mine doesn't? I know the problem lies with printf("The address of num is %d\n", *ptr); but did the line work on youtube but on my compiler it doesn't.

#include <stdio.h>

 int print_int_ptr();

 int main(){
   int num;

   num = 10;
   print_int_ptr(num);


   return(0);
 }
 /* dont forget that in between the assignment of ptr = &num */

 /* Take the address of an integer as a parameter, and print out both the
  * address and the integer itself
  */
  void print_int_ptr(int *ptr){

    printf("The address of num is %d\n", *ptr);
    printf("The value of num is %d\n", ptr);
  }

Solution

  • In main(), num is an integer. You passes it to print_int_ptr(int *ptr).

    int *ptr significates that the first argument for print_int_ptr() is a pointer, because int * declares a pointer. So as soon as you enter print_int_ptr(), ptr is considered as a pointer. But num = 10, so any reference to ptr will point out address 10, which, obviously, isn't right.

    That's exactly what you're doing with printf("The address of num is %d\n", *ptr);. *ptr dereferences the pointer, it tries to access the value at address 10. But you can't access a value at an arbitrary address, unless you're lucky and the OS gave exactly this one to the process.