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?
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
).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With