6

How to use malloc() in C++ program?

exebook
  • 32,014
  • 33
  • 141
  • 226
  • 1
    Looking at this question and some of your previous questions you seem to be confused about C versus C++. In general you shouldn't be using C library functions in C++ code (although there is nothing to stop you). – Paul R Jul 11 '10 at 08:59
  • 4
    @Gustly, the whole point of SO was to become the place that Google _sent_ you to for programming questions. That's why LMGTFY is never a valid response. By all means complain about a question for being a dupe or not programming related or too wishy-washy for a real answer, but don't send relevant questions (even the easy ones) across to somewhere else. – paxdiablo Jul 11 '10 at 09:01
  • And perhaps those closing for the "It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, or rhetorical and cannot be reasonably answered in its current form." reason can explain why that is the case. It seems definite enough to me. Maybe I'm mellowing in my dotage :-) – paxdiablo Jul 11 '10 at 09:04
  • 3
    `malloc` is just a function so you 'use' it by calling it, like any other function. It is more important to know what it doesn and why want to use it. What problem are you trying to solve that you think `malloc` is the answer to? – CB Bailey Jul 11 '10 at 09:58
  • @paxdiablo: now I want a feature to pre-emptively reopen, on the basis that I know now that I disagree with the reason for closure, but I won't necessarily return to this question again. If someone could find a dupe, that would be better... – Steve Jessop Jul 11 '10 at 13:47
  • @Steve, I usually "favourite" the questions and check back once a week. Once I cast my reopen, they then get unfavourited :-) – paxdiablo Jul 11 '10 at 14:10
  • It seems particularly perverse to say that something "isn't a real question", when 6 people have answered it, all apparently understood pretty much the same thing by it, and one of the answers was accepted. What is it that 4 people feel distinguishes this from the correct meaning of the word "question"? ;-) – Steve Jessop Jul 11 '10 at 14:14
  • 1
    @Steve: This question is vague and incomplete. (Note the description that comes with "not a real question".) The OP could make it acceptable by, for example, showing what he's tried, asking about specific (example) code, asking for clarification on docs he's read (i.e. quote the docs), etc. In addition, while you always judge a question based on its content, my experience with this poster's history says he will never fix these problems with the question, so I have no issue voting to close now rather than giving him a few days to fix it. –  Jul 11 '10 at 19:43
  • @Roger: if it's a bad question, I think that's what downvoting is for. However, it is a question. In addition to the things you list that are missing, it's missing an initial capital letter too, but personally I don't think that makes it "incomplete" either, in the meaning of the act. – Steve Jessop Jul 11 '10 at 23:22
  • @Steve: If you have an issue with the "not a real question" close reason itself, that's one thing (and better discussed on Meta), but it's just not a viewpoint I share. The description of that close reason appears, to me, to apply to this post, though perhaps the close reason name could be better. I did feel your comment expressed confusion over closing that I wanted to clear up -- especially that "too basic" wasn't involved and that this user has a history of asking vague and incomplete questions, then abandoning them. –  Jul 12 '10 at 02:07
  • For example, I don't expect the OP to respond to Charles' comment above, and answering that with a concrete example (even one copied from an exercise from elsewhere) could *really* improve this question. –  Jul 12 '10 at 02:11
  • 1
    @Roger: I have no problem with the "not a real question" close reason as defined by the site. It's excellent when you "can't tell what is being asked" - vague rambles, nonsense, etc. I am surprised if the five people who voted this closed can't tell what is being asked, hence I suspect that they are stretching the definition. I agree with you that the questioner has failed to improve the question (he has his answer, for one thing), but I don't agree with your position that "questioner failed to improve the question" has anything to do with this site's definition of "not a real question". – Steve Jessop Jul 12 '10 at 09:55
  • ... I'm uncertain whether "questioner refuses to improve the question" *should* be considered sufficient grounds to close, but I'm pretty sure that it does not constitute "not a real question". Just not a *good* question. And for instance I don't see why knowing what the questioner has tried has anything to do with whether the question is vague (as you state above). Incomplete surely means "can't be answered due to omissions", not "don't want to answer because I think the questioner is lazy due to omissions"? IMO you are punishing a bad questioner by closing questions. – Steve Jessop Jul 12 '10 at 09:58
  • No big deal, anyway. When I started this argument, someone else was the accepted answer, so now that I'm continuing it I look self-interested... – Steve Jessop Jul 12 '10 at 10:10
  • @Steve: Also, as one of the five, I honestly can't tell what's being asked – I can *guess* what he *might* want because I'm used to dealing with C and C++ questions, but that's not the same thing. Surely "malloc(1)", while a real example of how to use malloc, would not help anyone who truly needed an answer to this question: because it's not a real question in the first place and what he really wants to know hasn't been asked. –  Jul 12 '10 at 10:13
  • This is much more like what I think of as a vague question where it's difficult to tell what is being asked: http://stackoverflow.com/questions/3227255/question-about-location-of-variable-in-memory. Compared with that, this one is crystal clear ;-) – Steve Jessop Jul 12 '10 at 10:26

6 Answers6

9

You shouldn't use malloc in C++. You should use new instead. In fact, you probably shouldn't be using new as well (for most basic programming in C++). But still a basic example is declaring an array: int* array = new int[n]. This will allocated room for n integers and return a pointer to the address of the first one. Please note that you must explicitly call delete[] to free this allocation.

Shiroko
  • 1,437
  • 8
  • 12
7

Mostly, you shouldn't use it at all. C++ provides the new and delete operators for memory management, and even delete can be largely avoided by using smart pointers such as boost::shared_ptr from the Boost library.

Example:

// malloc
Duck* duck = (Duck*)malloc(sizeof(Duck));

// new
Duck* duck = new Duck();

Also note that, if the Duck class has a non-trivial constructor, then new is almost mandatory. (Almost, because you could use malloc with placement new, but that would be getting us off the main track).

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
5

Question 1: "How do I call malloc from C++?"

One of these two:

#include <cstdlib>

...

int *iptr = (int*) std::malloc(sizeof(*iptr));


#include <stdlib.h>

...

int *iptr = (int*) malloc(sizeof(*iptr));

As with C, you could use sizeof(int) if you prefer, rather than sizeof(*iptr).

Note however the (theoretical) need for the namespace if you use cstdlib. As Neil says, pretty much any implementation of <cstdlib> will put malloc in the global namespace, but this isn't guaranteed by the standard.

Also the (genuine) need for a cast, since C++ lacks C's automatic conversion of void* to other pointer types. You could use a static_cast rather than a C-style cast, but personally in this case I don't see the point.

As everybody says, there's little good reason to use malloc in C++. Interfacing with C code which requires a malloced pointer (because the C code will free it) is one good reason, but you can get into trouble even there if the two bits of code are in different dlls.

Question 2: "How do I allocate memory in C++?"

Normally you would do this:

int *iptr = new int;
int *intarrayptr = new int[23];
delete iptr;
delete[] intarrayptr;

Or for raw data to be used for some nefarious purpose that you can't represent as a C++ object / array, do this:

unsigned char *twentythreebytes = (unsigned char*) ::operator new(23);
::operator delete(twentythreebytes);

However, allocating memory off the heap like this is also quite rare in (well-designed, high-level) C++ code. Prefer automatic or member variables, and standard containers, where possible:

#include <vector>

...

std::vector<int> intarray(23);
// no need to delete: the array will be destroyed when it goes out of scope.
Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • Out of interest, what implementations do you know that remove malloc from the global namespace when cstdlib is used? –  Jul 11 '10 at 13:31
  • 1
    None that I'm aware that they do. But whether they do or not, I wouldn't notice. What implementations bother to *document* which standard headers put things in the global namespace? ;-) I mentioned the difference because someone new to C++ is going to have to learn at some point that in general `std` is the place where C++ headers define stuff. Functions from standard C admittedly are not the best examples to illustrate that. – Steve Jessop Jul 11 '10 at 13:37
  • @Neil: Updated to reflect your point, I hope. – Steve Jessop Jul 11 '10 at 13:42
  • 2
    Perl calls this the X-Y problem: the questioner wants to do X, thinks Y might be the way to do it and asks "how to Y?". The unhelpful answer is frequently "Never do Y", while your more useful response is "I think you're trying to do X, let me tell you how to do X". – Hudson Jul 11 '10 at 14:19
2

The new and delete operators are the preferred C++ alternatives to malloc() and free(), because they are aware and capable of invoking the constructors and destructors of classes, in addition to allocation and deallocation of memory:

Foo* foo_ptr = new Foo();
delete foo_ptr;  // this calls Foo::~Foo(), the destructor
Jesse Dhillon
  • 7,841
  • 1
  • 34
  • 34
0

The only time I have ever used malloc and free in C++ is to implement dummy-versions of the memory management routines:

#include <cstdlib>
#include <stdexcept>

void* operator new(size_t number_of_bytes) throw (std::bad_alloc)
{
    void* p = malloc(number_of_bytes);
    if (p == 0) throw std::bad_alloc();
    std::cout << "allocated non-array memory @ " << p << '\n';
    return p;
}

void* operator new[](size_t number_of_bytes) throw (std::bad_alloc)
{
    void* p = malloc(number_of_bytes);
    if (p == 0) throw std::bad_alloc();
    std::cout << "allocated     array memory @ " << p << '\n';
    return p;
}

void operator delete(void* p) throw ()
{
    if (p == 0) return;
    std::cout << "releasing non-array memory @ " << p << '\n';
    free(p);
}

void operator delete[](void* p) throw ()
{
    if (p == 0) return;
    std::cout << "releasing     array memory @ " << p << '\n';
    free(p);
}
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
-1

Using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete.

Another major reason is for using new & delete : they are much more portable while malloc/calloc.. are not(Also new calls constructors and delete calls destructors while malloc and free do not). You will normally never get a problem using new & delete also on different platforms with different processers, because they encapsulate all calls to the native malloc functions safely.

The new operator can be used to create objects of any type. It takes the following general form-

pointer-variable = new data-type;