Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is *array* memory allocated and freed in C and C++?

My question specifically is in regards to arrays, not objects.

There a few questions on SO about malloc()/free() versus new/delete, but all of them focus on the differences in how they are used. I understand how they are used, but I don't understand what underlying differences cause the differences in usage.

I often hear C programmers say that malloc() and free() are costly operations, but I've never heard a C++ programmer say this about new and delete. I've also noticed that C++ doesn't have an operation that corresponds to C's realloc().

If I were writing an equivalent to C++'s vector class, I would want to avoid copying the entire array when resizing it, but with new and delete you have to copy. In C, I would simply realloc(). It's worth noting that realloc() might just copy the entire array, but my impression was that it used the same pointer and allocated less space for it, at least when sizing down.

So my question is, how do the algorithms used by malloc() and free() differ from those used by new and delete. More specifically, why does the C way have a stigma of being more expensive, and why doesn't the C++ way allow resizing without copying?

like image 550
Imagist Avatar asked Dec 30 '22 17:12

Imagist


1 Answers

There's no real difference under the hood - usually the default new and delete operators will simply call through to malloc and free.

As for "the stigma of being more expensive", my theory is this: back in the day, every cycle counted, and the time taken by malloc really was significant in many situations. But by the time C++ came along, hardware was much faster and the time taken by the free store manager was proportionally less significant. The emphasis was shifting from efficient use of machine resources to efficient use of programmer resources.

Why C++ lacks a realloc equivalent, I don't know.

like image 136
RichieHindle Avatar answered Jan 09 '23 03:01

RichieHindle