문제

#include <stdio.h>
#include <string.h>

main()
{
    int an_int;
void *void_pointer = &an_int;
double *double_ptr = void_pointer;
*double_ptr = 10;

printf("%d", sizeof(*double_ptr));

}

Output of this program is 8.
How does this happens??
I mean double_ptr was pointing to 4 bytes memory but still output is 8 .
*Where does other 4 bytes comes from ??? This program should crash as other 4 bytes are not allocated to it. *
Please explain??

도움이 되었습니까?

해결책

C is statically typed, the expression sizeof *double_ptr is solely computed according to these static type rules, namely double_ptr points to a double which has size 8.

This program has undefined behavior, because you are writing to a memory range that you don't "own". All bets are off, it might crash or not. When doing such nasty conversions you are the responsible for that, not the compiler.

Edit, for nitpicks:

  • functions without return type should not be tolerated by a conforming compiler. increase the warning level.
  • when posting code here, please indent it properly
  • the result of the sizeof operator is not int but size_t an unsigned type. Printing that with "%d" also has undefined behavior. Use "%zu".

다른 팁

I mean double_ptr was pointing to 4 bytes memory but still output is 8.

This is because sizeof is evaluated based on the type or on the type of the expression. Moreover, in this case it can be fully evaluated at compile time, regardless of the pointer's value.

*Where does other 4 bytes comes from ???

They belong to a region of memory adjacent to the location of int. This region is not allocated to the object that you were intended to write, so it is undefined behavior. Good chances are that you are writing into the pointer itself, which could happen if the compiler places void_pointer in memory immediately after an_int.

This program should crash as other 4 bytes are not allocated to it.

Unfortunately, not all undefined behaviors lead to crashes. This is a common case in C when an invalid program does not crash. For example, all buffer overrun exploits rely on the ability of a program not to crash after exhibiting undefined behavior.

sizeof is compile time operator. so its checking the type of data that pointer may point (which is double 8 bytes) so the output is 8.

int main()
{
    int an_int;
void *void_pointer = &an_int;
double *double_ptr = void_pointer;
*double_ptr = 10;

printf("%d %d",*double_ptr,sizeof(*double_ptr));

} 

i have edited a bit. It crashes when it tries to access the memory using pointer.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top