When you call function(str)
, you are passing the value of str
to function
. This value is some uninitialized garbage value because you haven't set it to anything in main
, but that's not the problem.
The problem is that function
has its own pointer, var
, into which it puts that garbage value so that one could say var points to the same thing (garbage) that str points to
. However, they are not the same variable. They are two distinct variables, and changing var
has no effect on str
.
When you say var = (char*) malloc (100);
, you are allocating memory somewhere and then telling var
to point to it. Now var
points to a different location than str
. Immediately you return from that function, losing var
and the location of that memory. This by the way is a memory leak.
When you return back to main
, str
is as it ever was - pointing to garbage.
A numerical example:
char *str; // str -> 0xfeedface (garbage)
function(str);
// inside 'function', an initialization like this occurs
char *var = str; // var -> 0xfeedface (same garbage)
var = (char*) malloc (100); // var -> 0x12341234 (alloc'd memory)
return;
// back in 'main'
strcpy(str, "some random string"); // str still points to 0xfeedface!
To do this properly, you need to change str
s value. This means function
needs a pointer to str
, or a pointer to a pointer.
void function(char **var)
{
*var = (char*)malloc(sizeof(char) * 100);
}
int main()
{
char *str;
function(&str);
strncpy(str, "some random string", 99);
...
free(str); // important in general
}