2 bytes allocated problems

Dag-Erling Smørgrav des at des.no
Wed Feb 24 19:55:16 UTC 2010


Andrey Zonov <andrey.zonov at gmail.com> writes:
> Dag-Erling Smørgrav <des at 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 = malloc(10);
    strcpy(p, "abcdefghi")
    p += 5;

then *p == p[0] == '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] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' };

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

DES
-- 
Dag-Erling Smørgrav - des at des.no


More information about the freebsd-hackers mailing list