0
votes
#include <stdio.h>

  int main () {
      char c = 'A';
      int *int_ptr;
      double *double_ptr;

      *int_ptr = *(int *)&c;
      *double_ptr = *(double *)&c;

      printf("Original char = %c \n", c);
      printf("Integer pointer = %d \n", *int_ptr);
      printf("Double pointer = %f\n", *double_ptr);

      return 0;
  }

The questing is – Why can't I assign the double_ptr using this code, because it causes segmentation fault, but works fine for integer?

As I understand char is 1-byte long and int is 4-bytes long, so double is 8 bytes-long.

By using expression *(double *)&c I expect the following:

  1. & – Get the memory address of c.
  2. (double *) – pretend that this is a pointer to double.
  3. *() – get the actual value and assign it to double var.
2
1) You know what you're doing is "wrong". 2) If you're curious why you're getting a segmentation error, why don't you compile with -S (gcc) or /Fa (MSVC) and look at the assembly output? - paulsm4
First of all you don't have any memory behind the pointers so doing *int_ptr is addressing memory that doesn't belong to you, i.e. UB. You don't even know where as the pointer is uninitialized. Besides that you try to read a char (1 byte) using int (4 or 8 bytes) which again is UB. - 4386427

2 Answers

3
votes

Your code has Undefined Behaviour. Therefore anything could happen.

The UB is because you are casting a char which is one byte to types that are 4 and 8 bytes, which means you are (potentially) accessing memory out of bounds, or with the wrong alignment.

Whether any of this will "work" or "not work" on any particular system is not very relevant, because the code is erroneous.

2
votes

In your program, typecast of char to int* or double* and then a dereference would get some number of extra bytes from memory, which is undefined behavior.