ew @ straight C.
Anyway, for starters, you're not mallocing enough. You only alloc 25, but the string you're copying is much larger. This will lead to heap corruption and some very nasty, hard to find runtime bugs. Always watch for buffer overflow!!!
As for your actual problem:
Take the pointers out of the situation for a second. Consider the following code:
1 2 3 4 5 6 7 8 9 10 11 12
|
void func(int local)
{
local = 5;
}
int main()
{
int passed = 0;
func(passed);
printf("%d",passed);
return 0;
}
|
What this code does is pass the parameter
by value. That is... 'local' is a separate variable whose contents get
copied from 'passed'. However 'passed' is never changed throughout this process. So when func changes local to 5, 'passed' still is zero, and thus printf outputs "0".
This is exactly what you're doing. You're passing a pointer by value and expecting the function to change the pointer. It doesn't. See:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void func(char* local)
{
local = malloc(100); // changes local -- NOT passed!
}
int main()
{
char* passed; // points to nothing/garbage
func(passed); // passed is unchanged by this call
// so here, passed STILL points to nothing/garbage
printf("%s",passed); // bang, you're dead
return 0;
}
|
The solution to this is to either:
1) return the pointer rather than pass it as a parameter
1 2 3 4 5
|
char* func()
{
char* local = malloc(100);
return local; // okay
}
|
or 2) pass the pointer by reference (by pointer). IE: pointer to a pointer:
1 2 3 4 5 6 7 8 9 10 11 12
|
void func(char** local)
{
*local = malloc(100);
}
int main()
{
char* passed;
func(&passed); // this DOES changed 'passed'
free(passed); // don't forget to free it when done!
return 0;
}
|
EDIT: blech -- helios is too quick ;_;