CPlusPlus wrote:
> 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
>
There are various typos, header files not included &c here. After fixing
those, the big problem is this:
malloc(strlen("hello"+1)*sizeof(char))
You take the start address of the literal string "hello", add one to it,
and measure its length from there. In other words, rather than adding
one to the length of the string, to account for the terminating null,
you've effectively subtracted one. The strcpy() then writes off the end
of the allocated block of memory, evoking undefined behaviour.
The fix for this is pretty self-evident. BTW, this would probably be better
posted in a C newsgroup, as there's no C++ at all in this.
James
|