what is corresponding code in c++ for malloc

S

Sameer

Hi friends,
I am new to c++.
I have a code in C,

void *malloc();
code_value=malloc(100*sizeof(unsigned int));

// some code

free(code_value);

what is the corresponding code in c++ ?
 
A

Alf P. Steinbach

* Sameer:
Hi friends,
I am new to c++.
I have a code in C,

void *malloc();
code_value=malloc(100*sizeof(unsigned int));

// some code

free(code_value);

what is the corresponding code in c++ ?

std::vector<unsigned> code_value(100);

// some code, e.g. code_value[55] = 1234;

If you want to live dangerously you can of course do the allocation and
deallocation yourself,

unsigned* code_value = new unsigned[100];

// some code, e.g. code_value[55] = 1234;

delete[] code_value;

but then you run the risk of leaking memory if an exception occurs in
"some code", and anyway it's less convenient so not much of a choice.

If you want to live even more dangerously you can use the C library
facilities; they're part of standard C++, but with C++ you have to cast
the result of malloc (which you shouldn't do in C).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top