I am typecasting the address of a character variable whose address 0x7ffc684486ef to an integer pointer. The value at the address 0x7ffc684486ef is 16, when I dereference using the integer pointer it would read 4 bytes starting from address 0x7ffc684486ef, but it return value 0, how is it. Is my understanding wrong ?.
int main()
{
char var;
int *ptr;
ptr = (int *)&var;
printf("%p %p\n", &var, ptr);
*ptr = 16;
printf("%d %d\n", var, *ptr);
return 0;
}
O/P
0x7ffc684486ef 0x7ffc684486ef
16 0
- Why the below code does not print anything.
#include <stdio.h>
#define ADDRESS 0x7ffc684486ef
typedef struct Point {
int x;
int y;
}Point;
int main()
{
Point *var = (Point *)(ADDRESS);
var->x = 2;
var->y = 5;
printf("Location: %p\n", var);
printf("Values: %d %d\n", var->x, var->y);
}
O/P:
NIL
CodePudding user response:
C allows wildly unsafe pointer conversion such as ptr = (int *)&var;
without protesting. So it's likely that you get the same address even after changing the pointer type.
However, when you de-reference the *ptr = 16;
you invoke an impressive number of undefined behavior bugs: out of bounds access, possible misaligned access, strict aliasing violation, accessing memory you don't have access to, and so on. Don't do this, this code is incredibly broken and there's no telling what the result might be. What is undefined behavior and how does it work?
The second example is even worse:
- How do you know there is memory you have access to at that address?
- It's a misaligned address so you can't access it as a struct on most computers
- The access of memory areas unknown by the compiler, such as hardware registers, has to be
volatile
qualified.
So it would seem that you make a misaligned address somewhere out in la-la-land and this too is wildly undefined behavior. There's no point in reasoning about any behavior you might encounter. Any form of behavior can happen.
CodePudding user response:
Just to clarify the concept related to *p = 16 ... Look at this piece of code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int numa = -1, num, numb = -1;
int *p = (int *)#
*p = 16;
printf("\n%d %d %d %d", *p, numa, num, numb);
}
When it runs it will output:
16 -1 16 -1
Now try changing the data type to char on the line that declares 'num':
#include <stdio.h>
#include <stdlib.h>
int main()
{
char numa = -1, num, numb = -1;
int *p = (int *)#
*p = 16;
printf("\n%d %d %d %d", *p, numa, num, numb);
}
you will receive "Segmentation fault".