"I'm trying to figure out whether the compiler can understand if I give a hexa-string address to a function which requires a pointer as an argument."
"If I pass to the function print_something()
a value like &a
. It will work. But if I pass to it a value like 0x7ffeec6a1b5b
. Does it know that it is an address and accesses this memory block have this address?"
– Dũng Đào Xuân 2 mins ago
The compiler doesn't know nor care whether a passed address value denotes a valid memory address or not. It simply checks if the assignment to the pointer is done correctly.
Also 0x7ffeec6a1b5b
isn't a "hexa-string". It is an integer constant, which needs to be casted to the pointer type to be assigned:
"Pointer from integer/integer from pointer without a cast" issues
But if you later try to access this memory location with the hardcoded value by dereferencing the pointer, it invokes undefined behavior, if the address is invalid or used already (which is high-probably the case).
A segmentation fault says you that something with the memory allocation or memory access is not done correctly. The C standard does not mention segmentation faults explicitly because they are dependent upon implementation. It just classifies undefined behavior.
Memory addresses are given by the operation system usually to a requesting program.
You, as programmer, shouldn't care about where a specific object is stored exactly in the most times and you shouldn't attempt to use any specific address value in your code unless you code for an embedded system for example where you exactly can be sure for which address space you code.
So to answer you question:
Can I pass a hexa string as an address to a function as an argument in C?
Yes, of course. But doing any operations with treating that string or better integer as address will high-probably end up in undefined behavior. If it is well defined for your specific system, your program is nonetheless non-portable. So in general, it doesn't make much sense do so (exceptions excluded).
Side Note:
printf("%p\n", &a);
is strictly seen undefined behavior, too. The argument pointer needs to be cast to void *
-> ``printf("%p\n", (void*) &a);`