-1

I'm new to pointers, and I'm running some test code. I am aware that a segmentation fault means that I'm trying to access some piece of memory that I shouldn't be; however, I don't understand what's wrong with my line of thinking here.

int main(void) {
   int *ptr;
   *ptr = 400;
   printf("%d\n", *ptr);
   return 0;
}

The function compiles just fine. From my understanding, when ptr is declared, it has an arbitrary memory address. Then the second line puts 400 as a reference to that memory address. Finally, the printf() line should return 400, but it's giving me a core dump.

Can someone please clarify? I've looked at several pointer examples, and I thought I was getting the hang of it, until I tried this.

effunna9
  • 21
  • 5

1 Answers1

1

You don't have memory to write to. You need to allocate memory in order to be able to write to it. Otherwise you will (might) get an segmentation fault.

If you would have turned on compile time warnings clang would have warned you

prog.cc:6:5: warning: variable 'ptr' is uninitialized when used here [-Wuninitialized]
   *ptr = 400;
    ^~~
prog.cc:4:12: note: initialize the variable 'ptr' to silence this warning
   int *ptr ;

Here is the corrected code

#include <stdio.h>
#include<stdlib.h>
int main(void) {
   int *ptr = (int*)malloc(sizeof(int));
   *ptr = 400;
   printf("%d\n", *ptr);
   return 0;
}
schorsch312
  • 5,553
  • 5
  • 28
  • 57