Date: Wed, 24 Feb 2010 15:25:11 +0100 From: Max Laier <max@love2party.net> To: freebsd-hackers@freebsd.org Cc: Andrey Zonov <andrey.zonov@gmail.com> Subject: Re: 2 bytes allocated problems Message-ID: <201002241525.11930.max@love2party.net> In-Reply-To: <983a1cf21002240544s59006035ifbf0ef7eb045e44f@mail.gmail.com> References: <983a1cf21002240544s59006035ifbf0ef7eb045e44f@mail.gmail.com>
next in thread | previous in thread | raw e-mail | index | archive | help
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
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?201002241525.11930.max>