Reputation: 376
void foo (char *input) {
char *myVar;
*myVar = *input;
}
I understand that if I allocate myVar
memory using malloc(sizeof(char)
it will point to heap, but what if I don't allocate the memory, when I deference it, how the compiler handles the memory allocation? will it be allocated in stack or heap?
Upvotes: 0
Views: 201
Reputation: 409196
The variable myVar
is on the stack (for compilers which store local variables on the stack), but it doesn't point anywhere. That means when you dereference it you have undefined behavior.
Technically, the value of myVar
will be indeterminate (i.e. seemingly random) so it will point to a random location. This means that the dereference may sometimes cause a crash, while other times it may not.
Upvotes: 4
Reputation: 70941
when I deference it, how the compiler handles the memory allocation
Dereferencing a pointer's value (an address) is not allocating memory. Dereferencing just gives you access to the memory the reference, that is the pointer points to.
From where this memory had been allocated (if ever) depends on what had been assigend to the pointer. ls.
Note: Dereferencing an uninitialised pointer provokes undefined behaviour, as it does for any read-accees to uninitialised memory/variables.
Upvotes: 2