Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 24 Feb 2010 20:55:15 +0100
From:      =?utf-8?Q?Dag-Erling_Sm=C3=B8rgrav?= <des@des.no>
To:        Andrey Zonov <andrey.zonov@gmail.com>
Cc:        freebsd-hackers@freebsd.org
Subject:   Re: 2 bytes allocated problems
Message-ID:  <86sk8qpfx8.fsf@ds4.des.no>
In-Reply-To: <4B858007.1000008@gmail.com> (Andrey Zonov's message of "Wed, 24 Feb 2010 22:37:43 %2B0300")
References:  <983a1cf21002240544s59006035ifbf0ef7eb045e44f@mail.gmail.com> <86eikar7gv.fsf@ds4.des.no> <4B858007.1000008@gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
Andrey Zonov <andrey.zonov@gmail.com> writes:
> Dag-Erling Sm=C3=B8rgrav <des@des.no> writes:
> > Pointers have no boundareis in C.
> And how free() finds that the need to release?

That is a very simple question with a very complicated answer.  Whole
books have been written about the subject.  Normally, I'd say "look it
up on Wikipedia", but the Wikipedia article on dynamic memory allocation
is little more than a stub.  Try Knuth's The Art of Computer Programming
instead.

However, none of this changes the fact that pointers in C have no
boundaries.  In practical terms, a pointer is just a number that
refers to a particular location in memory.

If you do

    char *p =3D malloc(10);
    strcpy(p, "abcdefghi")
    p +=3D 5;

then *p =3D=3D p[0] =3D=3D 'f', and if printf("%s", p) will print "fghi".  =
What
happens if you then try to free(p) will vary from OS to OS and sometimes
between versions of the same OS; in most cases, either nothing will
happen at all, or your program will crash.

The reason printf() knows to stop after the 'i' is that the next char in
memory is 0.  That's why your program didn't work: there was no 0 there
to indicate the end of the string.  Sometimes it would seem to work
because there would, by coincidence, be a 0 there already, but that
doesn't mean your code is correct.

Why is there a 0 after the 'i'?  Because when you write "abcdefghi", the
compiler actually stores "abcdefghi\0".  That's the definition of
"string" in C: a sequence of characters immediately followed by a 0.  If
you don't want the 0 there, you have to do something like this:

    char a[9] =3D { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' };

but then you don't have a string, just an array of 9 chars.

DES
--=20
Dag-Erling Sm=C3=B8rgrav - des@des.no



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?86sk8qpfx8.fsf>