C++ Memory Management : What is the difference between malloc/free and new/delete?
来源:互联网 发布:折弯机编程 编辑:程序博客网 时间:2024/05/15 23:52
http://forums.codeguru.com/showthread.php?t=401848
Q: What is the difference between malloc/free and new/delete?
A : 'malloc()' is a function inherited in C++ from C. It is defined in '<stdlib.h>' in C and '<cstdlib>' in C++. Its main purpose is to request the OS (free store) for a bunch of memory bytes for you. You would make a call to 'malloc()' and the request goes to the operating system that allocates the requested amount of contiguous raw bytes if possible. I say "if possible" because under certain circumstances (like lack of memory), the request may not be successfully acknowledged. Let's take a look at the prototype:
Code:
void* malloc(size_t size);
- malloc @ cplusplus.com
- malloc @ msdn.microsoft.com
'free()' is a function inherited in C++ from C. It is defined in '<stdlib.h>' in C and '<cstdlib>' in C++. Its main purpose it to free the memory acquired explicitly by a call to 'malloc()'. That means, if you make a request for some bytes using 'malloc()' then when you are done with using those bytes you must return them back to whom you took it from. Every 'malloc()' call must be followed by a call to 'free()' else you get into a situation called a memory leak. That piece of malloc-ed memory remains unusable to your program as well as the OS, until your program ends. Of course, that is not good. Let's take a look at the prototype:
Code:
void free(void* memblock);
- free @ cplusplus.com
- free @ msdn.microsoft.com
'new' is a C++ operator. The task that you will use this for is still request for dynamic allocation of one object or multiple objects. On success, it returns a suitably typed pointer and on failure it would throw an exception ('std::bad_alloc'). There is a nothrow version of 'new' as well. C++ objects are different. They are constructed in basically two steps:
- first, allocation of requried amount of bytes and
- second, a successful call of the constructor.
Code:
class A { /*some members and a public constructor taking no arguments*/public: A() { /* ... */ }};int main(){ A* ptr = new A(); // (1) A* ptrToArrayOfAObjects = new A[10]; // (2)}
'delete' It is the counter-part of 'new' and also a C++ operator. The task that you will use this for is to free up memory acquired by a call to 'new'. For the allocations shown in the above code you will need to do the following:
Code:
class A { /*some members and a public constructor taking no arguments*/public: A() { /* ... */ } ~A() { /* ... */ }};int main(){ A* ptr = new A(); // (1) A* ptrToArrayOfAObjects = new A[10]; // (2) delete ptr; delete [] ptrToArrayOfAObjects;}
- it first calls the destructor of the object and then
- makes the deallocations.
You have to make sure you use the correct match of 'new' and 'delete'. According to the C++ standard:
- if you allocate with 'new' you release with 'delete'
- if you allocate with 'new[]' you release with 'delete[]'
By now, you should be able to understand the differences between 'malloc()'/'free()' and 'new'/'delete' but still I will put up some points to make it really explicit so as to kill any scope of confusions.
- 'malloc()' allocates a bunch of bytes while 'new' does the allocation as well as has the responsibility of calling the constructor.
- 'malloc' returns 'NULL' on failure while 'new' throws an exception object of type 'std::bad_alloc'. (There exists a nothrow version of 'new', though)
- 'malloc' is the C way of dealing with the free store while 'new' is the C++ way.
- Every call to 'malloc()' should be followed by a call to 'free()' while every call to 'new' should be followed by a call to 'delete'.
- 'free()' deallocates all bytes allocated by a prior 'malloc()' call (using the same pointer) while 'delete' makes a call to the destructor and then goes on with the deallocation.
- There are array forms of 'new' and 'delete' while 'malloc()' and 'free()' do not (as the request is for a specific size of raw memory in bytes).
- 'free()' on 'NULL' pointers is not safe while 'delete' is.
Notes:
- Do not mix the allocation and deallocation routines i.e. do not use 'malloc()' with 'delete' or 'new' with 'free()'.
- There are circumstances when you can use 'malloc()'/'free()' for C++ objects (POD as well as non-POD). For example, when managing a memory pool. There you explicitly call the constructor using 'placement new' operator syntax and the destructor. Let's keep that for later.
References:
- Item 3 : Prefer new and delete to malloc and free - from Effective C++ by Scott Meyers.
- Free-store management @ C++ FAQ Lite
- C++ Memory Management : What is the difference between malloc/free and new/delete?
- What is the difference between new/delete and malloc/free?
- Difference between new (delete) and malloc (free)
- What is the difference between new and malloc()?
- what is the difference between "delete []m_data"and "delete m_data"
- What is the difference between malloc and new other than syntax?
- What is the difference between XML and C or C ?
- The difference between "malloc" and "new"
- What is the difference between fprintf and vfprintf in C++?
- what is the difference between definition and declaration in c
- What is the difference between test, [ and [[ ?
- In Linux, what is the difference between “buffers” and “cache” reported by the free command?
- What is the difference between << and += while injecting elements to Hash.new([])?
- What's the difference between CUDA shared and global memory?
- what is the difference between the setTimeout and setInterval
- What is the difference between DHTML and the DOM?
- What is the difference between the mouseover and mouseenter events?
- What exactly is the difference between “pass by reference” in C and in C++?
- Android隐藏状态栏和标题栏,相当于全屏效果
- 左面图标改变的问题
- Failed to create java virtual machine
- 无聊,让人感到窒息的无聊
- 使用ckeditor上传图片
- C++ Memory Management : What is the difference between malloc/free and new/delete?
- adb:) adb shell am
- C#导出Excel后关闭进程(EXCEL.EXE)释放资源的解决方案
- Java 线程池的原理与实现
- 调整虚拟机中Ubuntu Server 屏幕分辨率
- 9 10 章
- PHP 数据库(mySQL)安全性配置
- c++断言机制的应用
- 三态门