Guidelines for memory management and avoiding leaks?

I am wondering if there are any rules/good practices I should follow for avoiding memory leaks.
Now and then I am developing some useless app for R5/Haiku (which I never finish by the way :-)), and every time I encounter problems and questions concerning memory management.

Are there any rules for stack allocation vs heap allocation?
For instance when sending a message, is it better to allocate it on the stack:

BMessage msg(B_SOME_CONSTANT);
BMessenger->SendMessage(&msg);

or do I allocate it on the heap?

BMessage *msg = new BMessage(B_…);
BMessenger->SendMessage(msg);
delete msg;

Or doesn’t this matter at all?

I am also wondering if objects like a BStringView make a copy of the data it’s arguments make a reference to:

//Allocate them on the heap
char* name = “newbie”;
char* title = “question”;

//pass them to the stringview
BStringView(BRect(0,0,50,20), name, title);

//Is it allowed to delete them??
delete name;
delete title;

Is the above allowed, or do I need to preserve the allocated Strings?
If you’re thinking why I am not trying it out; i’m at work and want to know now :slight_smile:

These questions may be a little too much about C++ in general, but I can imagine they are Beos/Haiku specific too.
Are there any facilities in the OS to assist in memory management?

You might want to ask this on a mailing list, developers are most active on there.

http://www.haiku-os.org/community/ml

Of course, that is if one of them does not reply here first.

If you keep the ownership of the object (that is you do your delete ptr, it isn’t the library that does that), and as an stack-allocated object it wouldn’t go out of scope when you still need it, then it doesn’t matter very much. If it is a large object, like in kilobytes, you should allocate it on the heap so you don’t exhaust your stack. If it is small, then allocate it on stack as it’s faster.

char *ch = “elomelo” doesn’t really allocate the data on the heap: “elomelo” will be present in a read-only data section all the time the program (or library) is in memory. The pointer ch to that data, on the other hand, is stack allocated in this example.