-3

Trying to understand what exactly happens in the memory during the execution of this code and why it causes a segmentation error.

#include <stdio.h>

int main() {
    int* ptr;
    *ptr = 5;
    printf("%d", *ptr);
    return 0;
}
M Oehm
  • 28,726
  • 3
  • 31
  • 42
  • 2
    `*ptr = 5` attempts to write `5` to the address held in `p`. Questions: what _is_ this address? Do you have permission to write to it? – ForceBru May 03 '19 at 16:34

2 Answers2

2

All variables must first be initialized to a valid value before you can use them in an expression like *p. For pointers, this means assigning an address to point to. You can do this either by taking the address of another variable or by dynamically allocating memory with malloc().

When you try to dereference an uninitialized pointer with *p, it will use whatever memory address happens to be stored in p at that time. Most likely this address is invalid for you to use and so you get a segfault.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

First allocate memory to the pointer variable

ptr = (int* ) malloc(sizeof(int))
ForceBru
  • 43,482
  • 10
  • 63
  • 98
Mani2019
  • 1
  • 1