Which one should I use, malloc or new?

Asked 2 years ago, Updated 2 years ago, 133 views

In C++, there are many ways to dynamically allocate, right? Then when should I use malloc and when should I use new?

malloc If you finished free If new is done, delete I know I shouldn't mix the two.

c++ memory-management malloc new-operator

2022-09-22 22:30

1 Answers

Do not use malloc unless you have to write C. Write new only. And free and delete have different ways to write.

char *pBuffer = new char[1024]; In situations where large memory is allocated, such as

delete pBuffer; This is not the exact way. Only one element can be delete or the heap can be damaged.

To delete the data in the array instead, write: delete[] pBuffer;

Also, new is different from malloc. new calls the constructor according to type This is a type safe method rather than writing malloc.

However, data buffer to alter the size of the malloc It's better to use . new is realloc. extend the reduced size as effectively memory. There is no ability to make it. To change the size of the delete to allocation must be again.


2022-09-22 22:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.