Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of new and delete in C++

Tags:

c++

I need help in understanding when shall I use the following options

char *a = new char();

and

char *a = new char[sizeof(int)+1];

and how the respective memory freeing calls should be made?

like image 253
user987316 Avatar asked Nov 27 '22 09:11

user987316


2 Answers

Any time you use new T, you have to call delete on the resulting pointer afterwards.

Any time you use new T[n], you have to call delete[] on the resulting pointer afterwards.

And that's really all there is to it.

But note that you typically shouldn't use them at all.

If you need a string, don't allocate a char array. Just declare a std::string (without using new). If you need an array whose size is determined at runtime, don't allocate an array. Declare a std::vector (without using new).

like image 183
jalf Avatar answered Dec 10 '22 21:12

jalf


The fist one allocates a single char. You delete it with:

delete a;

The second one allocates an array of chars. The length you have chosen is a little strange. You deallocate it with:

delete[] a;

Now... I hope you don't think you can put a stringified number in the second a (something like "123456", because you'll need many more bytes. Let's say at least 12 if an int is 32 bits. There is a funny formula to calculate the minimum length necessary. It's an approximation of the log10 https://stackoverflow.com/a/2338397/613130

To be clear, on my machine sizeof(int) == 4, but in an int I can put -2147483648 that is 10 digits plus the -, so 11 (plus the zero terminator)

like image 24
xanatos Avatar answered Dec 10 '22 21:12

xanatos