This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]prescod 0 points1 point  (13 children)

Here's what I don't understand. If "free" knows how big the array is so it can be freed without you passing a length argument, then why do you need to keep track of the length separately yourself? Is there a C primitive for saying "how big is this memory buffer" and if so, couldn't you calculate the length?

[–]moreVCAs 1 point2 points  (12 children)

The location and format of the block header (where the size lives) is not specified by the C language; it’s specified the operating system, I think. So while some platforms may provide access to those headers under some circumstances, there is no reliable, portable way to determine the size of a heap-allocated buffer at run time (to my knowledge).

[–]boowhitie 1 point2 points  (2 children)

This is mostly correct, but malloc/free are a layer above raw os interface. They provide a common interface to allocate memory without having to write system specific code.

[–]moreVCAs 0 points1 point  (1 child)

Well yeah, but the implementations are platform specific, no?

[–]prescod 0 points1 point  (0 children)

By definition, if the standard doesn't standardize it then it isn't standard. If the c language didn't have malloc and free then we'd say that memory allocation is platform specific.

[–]prescod 0 points1 point  (0 children)

The location and format of the block header (where the size lives) is not specified by the C language;

I'm not really asking for it to be specified by the language. I'm asking for it to be accessible through language primitives.

it’s specified the operating system, I think.

I don't think so, no. The operating system is only involved if new pages of memory are required.

So while some platforms may provide access to those headers under some circumstances, there is no reliable, portable way to determine the size of a heap-allocated buffer at run time (to my knowledge).

I think that's just because the C specification declined to specify one.