2 bytes allocated problems

Max Laier max at love2party.net
Wed Feb 24 14:25:17 UTC 2010


On Wednesday 24 February 2010 14:44:35 Andrey Zonov wrote:
> Hi,
> 
> When I try allocated pointer to a pointer, and in it some pointers
> (important: size is 2 bytes), the pointers lose their boundaries.
> Why it can happen?
> 
> Test program in attach.

Your test program is broken:

>#define S1 "ab"
>#define S2 "cd"
>
>        pp = (char **) Malloc(2 * sizeof(char *));
>
>        pp[0] = (char *) malloc(2);
>        memcpy(pp[0], S1, 2);
>        pp[1] = (char *) malloc(2);
>        memcpy(pp[1], S2, 2);
>
>        printf("%s\n", *pp);
>        printf("%s\n", pp[0]);
>        printf("%s\n", pp[1]);

Why should *pp == pp[0], or pp[1] be a nul-terminated string?  You just copied 
the two characters.  It's pure luck if there is a \0 at the end of any of 
these elements, or that the access doesn't cause a SEGV.

If you do:

>        pp[0] = (char *) malloc(3);
>        memcpy(pp[0], S1, 3);
>        pp[1] = (char *) malloc(3);
>        memcpy(pp[1], S2, 3);

instead, you copy the termination and things work as expected.

Regards,
  Max


More information about the freebsd-hackers mailing list