malloc/free question
D'Arcy J.M. Cain
darcy at druid.uucp
Thu May 3 23:53:27 AEST 1990
In article <6822 at jarthur.Claremont.EDU> dfoster at jarthur.Claremont.EDU (Derek R. Foster) writes:
>In article <1990Apr28.020711.8639 at druid.uucp> darcy at druid.UUCP (D'Arcy J.M. Cain) writes:
>>Well I have never seen the source for a malloc and I don't know how it is
>>normally done but a moment's thought will suggest that the above can't work.
>>Consider the following:
>> char *ptr = malloc(64);
>> strcpy(ptr, "Stomp on the malloc structure");
>> free(ptr);
>
>Wellllll.... not necessarily.
>Remember, malloc usually allocates a few more bytes than you ask it to.
>The extra info could be stored at the beginning of the structure
Here is the original suggestion I was responding to:
<I suggested that malloc probably returns a pointer to a structure that has
<a pointer to the "allocated" memory and also the number of bytes that were
<allocated, so, when the free function is called using the pointer to the
<structure, free uses the bytes allocate member of that structure to
<"de-allocate" the memory.
And all I tried to say was that that couldn't work. Any implementation
*MUST* return a pointer to actual memory that the caller can write to. If,
as the first poster suggested, malloc returned "a pointer to a structure
that has a pointer to the allocated memory ..." then the above strcpy would
be impossible.
So if everyone would please stop sending me mail explaining how malloc
works?
--
D'Arcy J.M. Cain (darcy at druid) | Government:
D'Arcy Cain Consulting | Organized crime with an attitude
West Hill, Ontario, Canada |
(416) 281-6094 |
More information about the Comp.lang.c
mailing list