new vs. malloc

Can someone explain the difference between these two lines?
Yes I know one is c++ and the other is c. What I am trying to understand is the functional difference. I taught myself c and c++ but as I am now actually reading a book on c++ I am discovering that about 90% of my programming knowledge is straight c. I know c++ boasts dynamic memory, but I don't really understand why. These two functions appear to actually perform the same operation. I know that with c++ I can intentionally deallocate the memory but can't realloc be used to do the same thing ( or change the memory allocation )?

1
2
	int * thing1 = new int;
	int * thing2 = (int*)malloc(sizeof(int));
For an object of type int, the differences are minor:

They call different functions (you can provide your own function to be called by new within the same program, but you have to resort to the OS help to replace malloc)

They handle errors differently (new will call the user-provided handler if one was provided and throw an exception, while malloc would return a null pointer)

The cleanup is different (delete and free, respectively)
Last edited on
The big difference is that new will call an object's constructor, whereas malloc will not.

This of course does not matter with basic types like int (which is why Cubbi didn't mention it), but for complex types like std::string, using malloc will leave the object in an uninitialized state which will lead to very strange behavior and/or program crashes.


Likewise, delete calls destructors, whereas free does not.
Interesting. Thanks for the great explanation!

does that mean that new will behave just like malloc if I do something like this?


int * thing1 = new(nothrow) int;
This still calls the ctor.

Aceix.
Hi Dan,

My 2 cents worth of advice after the gold already offered !!

I am discovering that about 90% of my programming knowledge is straight c.


I hope that you learn to use the STL containers & algorithms as quickly as possible: to avoid mixing C++ and C programming. It's just that it is a common mistake to write loops to process things one at a time, when there is very often an C++ algorithm that will process a whole container worth of stuff for you.

I know c++ boasts dynamic memory, ....


malloc is a type dynamic memory for C. A bit pedantic I know ....

With C++03, people were taught to use new and delete, but big problems exist with this idea - namely when an exception is thrown before code reaches the call to delete. This idea might be rushing you a bit, but here goes ...

With C++11, we have RAII (Reference Acquisition Is Initialisation) smart pointers, which don't suffer this problem. So people are now taught to use these, and never use new and delete again. However it is still good to know how they work because they exist in recent production code, one day you may be forced to work with them.

does that mean that new will behave just like malloc if I do something like this?


I hope this doesn't imply you are trying to make your C++ program mimic the functionality of a C program? I might be wrong about what you are thinking, so apologies if this is the case. It's just that C++ does a lot of things (not all) better than C, and I hope you can embrace the better flexibility & robustness (at least less work to ensure it doesn't break) of C++

Any way just putting ideas out there man, hopefully they are potentially useful for you, if not now then some time in the future. If you already know all this (it's hard to guess how much people know), then no harm done :+)

Regards



There is placement new too. It does not allocate. It only calls ctor.

malloc allocates from heap.
new allocates from free store. Free store can be a heap, but not necessarily the same heap that malloc uses. Early compilers might have implemented new with malloc.

In any case you cannot mix the two systems, i.e. you may not allocate with new and then call free.
With C++11, we have RAII (Reference Acquisition Is Initialisation) smart pointers

A bit of a nitpick, but both RAII and smart pointers predate C++98: RAII was developed in late 80s, hand-in-hand with exceptions, and smart pointers were commonplace in third-party libraries in early 90s. Two of them were proposed in 1994 for inclusion in C++98, but there were too many competing implementations of shared_ptr, so none was chosen. Still, C++98 got auto_ptr, which was a smart pointer.
Cheers Cubbi :+)

Now that you mention it, I think you had reminded of that in the past - I had forgotten until just now. Hopefully the third time around I will get it right !

Anyway, I wonder how many new C++ coders mess about with 3rd party libraries? If anyone was anything like me, then learning was 1 or 2 hours here & there, so I was flat out just learning the elements of C++ and the STL.

Also, the OP mentioned new & delete, so I thought I would mention smart pointers as a better way of doing the same thing. I should also mention that this quote was something Herb Sutter said (paraphrased):

Herb Sutter wrote:
With C++03, people were taught to use new and delete, but big problems exist with this idea - namely when an exception is thrown before code reaches the call to delete. So people are now taught to use these [smart pointers], and never use new and delete again.


Right have to go to bed, it's 3 hours past my bed time !

P.S I am like the OP - self taught in C & C++, plus others learnt elsewhere.
Herb is trying to sweep auto_ptr under the rug :)

I wonder how many new C++ coders mess about with 3rd party libraries?

I guess it depended on the company you worked for. People were taught some basics, but then had to learn a lot more on the job.
Last edited on
Alright I am still up ! Couldn't resist learning something new.

Herb is trying to sweep auto_ptr under the rug :)


Hmmm, I was thinking he meant use the most appropriate of the 4 smart pointers, rather than new & delete. But something tells me I should read more about auto_ptr, no, I should read more about all of them.

I guess it depended on the company you worked for. People were taught some basics, but then had to learn a lot more on the job.


Ah, the rate of learning something if it is your job! It is much harder if one is trying to do something else concurrently - whether it be one's other university subjects, or one's somewhat unrelated job. For me as an Engineering Surveyor, it has only been a handful of times I have been able to write code (had permission and or time) to improve productivity at work. For me, the rest of the time it is a bit of dabbling here & there. With rate of learning, there was some software I had been told it would take a year or more to learn if one was working their normal job. I was lucky enough to have a lot of spare time on a particular construction project, so managed to learn a productive amount in about 2 weeks full time.

People were taught some basics .....


Yes, being taught formally is way different to teaching oneself, but info learnt from forums such as this is gold too - in class one (well not me anyway) doesn't get any input from experts like we do here, or at programmers place of work.

Hope this is all interesting for the OP - I might have pulled it off topic quite a bit.

Will now definitely hit the sack, 5 hours sleep might be just enough to soldier on at work with a head cold as well. Will need coffee & pseudoephredrine (Sudafed PE)

regards

Topic archived. No new replies allowed.