Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
new и delete?new void * __cdecl operator new(size_t sz)
{
return dlmalloc(sz);
}
[Note: unless an allocation function is declared with a non-throwing exception-specification(15.4), it indicates failure to allocate storage by throwing a std::bad_alloc exception (Clause 15, 18.6.2.1); it returns a non-null pointer otherwise. If the allocation function is declared with a non-throwing exception-specification, it returns null to indicate failure to allocate storage and a non-null pointer otherwise.—end note]
new в программе. Что будет происходить, когда new вместо выбрасывания исключения вернет нуль, а программа, справедливо не ожидающая такого подвоха, его разыменует? UB будет происходить. Любой код, содержащий любые, даже маловероятные (закон Мерфи, как известно, работает), предпосылки к UB может быть отправлен исключительно в мусорку. (Если это не очередная иллюстрация — «смотрите, а еще UB можно сотворить вот так»).#include <cstdlib>
int main()
{
return (size_t)malloc(112);
}
#include <stdlib.h>
void * malloc(size_t sz)
{
return (void*)42; //cannot print from here, as printf or puts can use malloc inside
}
cc -c -Wall my_malloc.c
g++ -c -Wall test.cpp
g++ test.o my_malloc.o -o test
./test
echo $?
Не секрет, что стандартный аллокатор new/delete/malloc/free в языке C/C++ не блещет быстродействием. Конечно, всё зависит от реализации, но, если говорить об оной от компании Microsoft, то это факт.
To my knowledge, nedmalloc is among the fastest portable memory allocators available, and it has many features and outstanding configurability useful in themselves. However it cannot consistently beat the excellent system allocators in Windows 7, Apple Mac OS X 10.6+ or FreeBSD 7+ (and neither can any other allocator I know of in real world testing).www.nedprod.com/programs/portable/nedmalloc/
Использование альтернативного аллокатора памяти в проекте на C/C++