C
CPlusPlus
typedef struct dummy // global definition
{
char* p1;
char* p2;
}d;
d d1;
void foobar()
{
// allocate memory from heap
d1.p1 = (char*)malloc(strlen("hello"+1)*sizeof(char));
strcpy(d1.p1, "hello");
}
void main()
{
foobar();
printf("d1.p1 = %s\n", p1.d1); // PROBLEM: junk is printed.
free(d1.p1);
}
I think I know why junk is printed because when foo exits, p1 data
vanishes, i.e, goes out of scope. How can I fix this?
Bare with me, I started out on writing a C++ program in MS VS2005 but
C has me figuring it out.
Thanks
{
char* p1;
char* p2;
}d;
d d1;
void foobar()
{
// allocate memory from heap
d1.p1 = (char*)malloc(strlen("hello"+1)*sizeof(char));
strcpy(d1.p1, "hello");
}
void main()
{
foobar();
printf("d1.p1 = %s\n", p1.d1); // PROBLEM: junk is printed.
free(d1.p1);
}
I think I know why junk is printed because when foo exits, p1 data
vanishes, i.e, goes out of scope. How can I fix this?
Bare with me, I started out on writing a C++ program in MS VS2005 but
C has me figuring it out.
Thanks