Can somebody help me explaining the following code:
Why the char *s doesn’t receive the point location of memory allocated at foo()?
#include <stdio.h>
#include <stdlib.h>
char *foo()
{
char *s = (char *)malloc(20);
s = "Hello Heap.";
return s;
}
void bar(char *s)
{
s = foo();
printf("bar: %s\n", s); // Works fine just as expected.
}
int main()
{
char *s;
bar(s);
printf("%s\n", s); // Output some undefined content like `H?}?H??`, other than `Hello Heap.`
}
The code fixed
Explanation:
1) Your code contains:
This not good. In this way you are not copying the
"Hello Heap."message into the allocated memory. In fact you have pointed the s pointer to allocated memory and then you have pointed your pointer to a constant string address2) Your code contains
in this function
sis getting the pointer (pointer to allocated memory) from thefoo()function. but you are not communicating thespointer address to the function higher leve (main). to do you have to return the address ofsat the end of the function or you can pass via address of address of pointer by using input parametercha ** s