473,574 Members | 2,875 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using malloc in C++?

I have read in Bjarne Stroustrup that using malloc and free should be
avoided in C++ because they deal with uninitialized memory and one
should instead use new and delete.

But why is that a problem? I cannot see why using malloc instead of new
does not give the same result.
Jun 7 '07
71 19052
Gianni Mariani wrote:
Ian Collins wrote:
....
>>
>>malloc(0)

Specified as far as you will either get a pointer to a block of >0 bytes
or NULL, just like any other size.

That would be a problem then.

Why? What ever you get from malloc, you can pass to free.

--
Ian Collins.
Jun 7 '07 #11
Ian Collins wrote:
Gianni Mariani wrote:
>Ian Collins wrote:
....
>>>malloc(0)
Specified as far as you will either get a pointer to a block of >0 bytes
or NULL, just like any other size.
That would be a problem then.

Why? What ever you get from malloc, you can pass to free.
Different behaviour on different systems. If I write code that assumes
malloc(0) returns unique values and it returns 0 on some, it will break.

I'm not sure if that's the only one but it is a source of inconsistency
between platforms.
Jun 7 '07 #12
Jim Langston wrote:
"desktop" <ff*@sss.comwro te in message
news:f4******** **@news.net.uni-c.dk...
>>I have read in Bjarne Stroustrup that using malloc and free should be
avoided in C++ because they deal with uninitialized memory and one should
instead use new and delete.

But why is that a problem? I cannot see why using malloc instead of new
does not give the same result.

(Untested code)

class Foo
{
int MyInt;
std::string MyString;
};

int main()
{
Foo* Bar = new Foo;
Foo* Screwed = malloc( sizeof( Foo ) );
}
I know the code is untested but for the OP I will add that another problem I
have with malloc vs new is that malloc requires casting. You see in C++ you
don't have the C feature of void* implicitely casts to any* (only the
reverse still exists). Thus the code above doesn't compile and to make it
compile you actually need to make something like
Foo* Screwed = static_cast<Foo *>(malloc(sizeo f(Foo)));

Clearly this is painful so better use "new". Not to mention malloc is error
prone because you may mistake the size of allocated memory (especially when
working on some other's people code) and you may allocate for another size
than the one for the type you need. While with new you have the "syntax
sugar" to just say I want an object of type T and everything is done
automatically (allocated memory to hold a sizeof(T), and returns a
converted T*).

--
Dizzy

Jun 7 '07 #13
Gianni Mariani <gi*******@mari ani.wswrote in
news:46******** *************** @per-qv1-newsreader-01.iinet.net.au :
Ian Collins wrote:
>Gianni Mariani wrote:
>>Ian Collins wrote:
....
malloc(0)
Specified as far as you will either get a pointer to a block of >0
bytes or NULL, just like any other size.
That would be a problem then.

Why? What ever you get from malloc, you can pass to free.

Different behaviour on different systems. If I write code that
assumes malloc(0) returns unique values and it returns 0 on some, it
will break.

I'm not sure if that's the only one but it is a source of
inconsistency between platforms.
You need to check for the 0 anyway as that represents a failure to allocate
the memory. However you do end up with the indeterminate behaviour of "did
the memory allocation of 0 succeed, and I can continue to some sort of loop
(which will execute 0 times) and then free the pointer, or did it fail and
we need to do some sort of memory exhaustion error handling?", since the
malloc(0) could appear to be either case.
Jun 7 '07 #14
Gianni Mariani wrote:
Ian Collins wrote:
Gianni Mariani wrote:
Ian Collins wrote:
....
malloc(0)
Specified as far as you will either get a pointer to a block of
>0 bytes or NULL, just like any other size.
That would be a problem then.
>
>
Why? What ever you get from malloc, you can pass to free.

Different behaviour on different systems. If I write code that
assumes malloc(0) returns unique values and it returns 0 on some, it
will break.

I'm not sure if that's the only one but it is a source of
inconsistency between platforms.
It's ALWAYS possible that malloc() could return a null pointer.


Brian
Jun 7 '07 #15
desktop wrote:
I have read in Bjarne Stroustrup that using malloc and free should be
avoided in C++ because they deal with uninitialized memory and one
should instead use new and delete.

But why is that a problem? I cannot see why using malloc instead of
new does not give the same result.

As the others have pointed out, new invokes the constructor for types
that have one. Reasons to always use new:

1. Somewhat friendlier syntax, as malloc() requires a cast unless the
results are assigned to a void*, and you usually do some arithmetic in
the size calculation. Examples:

int* arr = static_cast<int *>(malloc(5 * sizeof *arr));

int* arr = new int[5];

2. It gives a more consistent allocating scheme, so that you don't have
a mix of new and malloc(). Of course, one of the pitfalls of C++ is the
difference between new and new[], requiring delete or delete[]. There
is only one deallocation for malloc().

3. If you change your mind on a previously POD-type struct, you won't
have to find and change the malloc() calls.


Brian
Jun 7 '07 #16
On Thu, 07 Jun 2007 21:12:33 +1200, Ian Collins wrote:
Torsten Mueller wrote:
>desktop <ff*@sss.comsch rieb:
>>I have read in Bjarne Stroustrup that using malloc and free should
be avoided in C++ because they deal with uninitialized memory and
one should instead use new and delete.

But why is that a problem? I cannot see why using malloc instead of
new does not give the same result.

But there's another major reason for using new and delete: they are
much more portable while malloc/calloc/alloca/realloc/... are not. You
will normally never get a problem using new and delete, also on
different plattforms with different processors, because they
encapsulate all calls to the native malloc functions safely. These
operators belong to the language itself, not to the runtime library.
So you will normally not find includes of different headers and calls
to different allocation functions (both handled by conditional
compilation) and complicated casts for heap objects in strict C++
programs.
I don't follow that paragraph, what isn't portable about the malloc
family of standard library functions?
Time for me to open mouth...Insert foot...Yep, it fits...

But, if my assumption is correct, that new and delete can be
reimplemented (I think I read that somewhere), then yes, malloc and free
would seem less portable in a class hierarchy since they only work on
heap memory. Suppose new and delete are reimplemented to do weird stuff
like using a non-standard memory pool. Granted, I've never had a reason to
do such an esoteric mess but what then?

Jun 7 '07 #17
no***@all.com wrote:
On Thu, 07 Jun 2007 21:12:33 +1200, Ian Collins wrote:
>Torsten Mueller wrote:
>>desktop <ff*@sss.comsch rieb:

I have read in Bjarne Stroustrup that using malloc and free should
be avoided in C++ because they deal with uninitialized memory and
one should instead use new and delete.

But why is that a problem? I cannot see why using malloc instead of
new does not give the same result.
But there's another major reason for using new and delete: they are
much more portable while malloc/calloc/alloca/realloc/... are not. You
will normally never get a problem using new and delete, also on
different plattforms with different processors, because they
encapsulate all calls to the native malloc functions safely. These
operators belong to the language itself, not to the runtime library.
So you will normally not find includes of different headers and calls
to different allocation functions (both handled by conditional
compilation ) and complicated casts for heap objects in strict C++
programs.
I don't follow that paragraph, what isn't portable about the malloc
family of standard library functions?

Time for me to open mouth...Insert foot...Yep, it fits...

But, if my assumption is correct, that new and delete can be
reimplemented (I think I read that somewhere), then yes, malloc and free
would seem less portable in a class hierarchy since they only work on
heap memory. Suppose new and delete are reimplemented to do weird stuff
like using a non-standard memory pool. Granted, I've never had a reason to
do such an esoteric mess but what then?
Then the application that uses this non-standard memory pool isn't portable.

--
Ian Collins.
Jun 7 '07 #18
Default User wrote:
Gianni Mariani wrote:
....
>Different behaviour on different systems. If I write code that
assumes malloc(0) returns unique values and it returns 0 on some, it
will break.
....
>
It's ALWAYS possible that malloc() could return a null pointer.
Yes. The inference being my code will now magically work ?

How does this not break code that assumes a non-failure case returns
non-null ?
Jun 7 '07 #19
Gianni Mariani wrote:
Default User wrote:
Gianni Mariani wrote:
...
Different behaviour on different systems. If I write code that
assumes malloc(0) returns unique values and it returns 0 on some,
it will break.
>

...

It's ALWAYS possible that malloc() could return a null pointer.

Yes. The inference being my code will now magically work ?

How does this not break code that assumes a non-failure case returns
non-null ?
I don't understand the question. What results would you expect from
malloc(0)? Why would the implementation-defined nature make a
difference? Even when malloc(0) "succeeds", that is returns a non-null
pointer, you can't access the allocated memory. All you can do is
compare the pointer for equality or pass it to free().


Brian
Jun 7 '07 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2259
by: Christof Krueger | last post by:
Hello, I'm quite new to C++ and have some base C knowledge. So I know how to solve a given problem, by I sometimes tend to fall back to C. That is what I want to avoid in my current project. Therefore I have the following question: I maintain a list of objects that are created. There is some information that is logically related to each...
17
2421
by: Johs32 | last post by:
When I make a pointer I have read that if I would like to use it in another function, I need to malloc it first else it will disapear after the function returns. In this code I do not use malloc, but it still works and the function print_me() prints the correct text. Why does it work eventhough I do not use malloc? johs
8
7707
by: jmbn2k | last post by:
Hi Can anyone pls teme how to allocate memory using malloc in a 3 D diemensional array.............
0
1297
by: jmbn2k | last post by:
Hii Can anyone pls teme...how to allocate memory using malloc in a 3 D dimensional array........
13
9690
by: shsingh | last post by:
I have a class A containing some map as data variables. I creat an object of class A on heap by allocatiing memory by using "malloc". This will return me the required memory but the object is not initialized properly as constructor same is not get called ( as per the behavior). How to call a constructor explicitly if we want to allocate...
2
1730
by: aziizvu | last post by:
Write a program using malloc function. In which you take input from user and allocate memory equal to square of this number. Which multiply numbers and draw a table in the following format? Hint: User enters 3 then program allocates equal to 9 integer memories. Output:1 Enter a single digit number: 2 The multiplication table of 2 is:...
8
2456
by: digz | last post by:
I saw the following code and comments in a source file, I am not able to appreciate what the author is trying to do in ALIGNED_ALLOC , can some one plz help me understand why CACHE_LINE_SIZE * 2 is first added to the parameters to malloc and then CACHE_LINE_SIZE -1 is added to the return address and after that its bit anded with (...
0
7753
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8095
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8265
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7847
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6500
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5332
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3769
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3787
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1365
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.