tags:

views:

249

answers:

8

I think all malloc(sizeof(structure)) can be replaced this way:

char[sizeof(structure)]

Then when is malloc necessary?

A: 

When you don't know how much memory to allocate at compile time. Take a very simple program, where you need to store the numbers entered by the user in linked list. Here you dont know how many numbers will be entered by the user. So as user enters a number you will create a node for it using malloc and store it in the linked list.

Naveen
+4  A: 

You should read about dynamic memory allocation. You obviously don't know what it is.

The main difference between the two is that memory allocated with malloc() exists until you say so. Static memory such as char buff[10]; only exists in the function scope.

Luca Matteis
+15  A: 
  • When you don't know how many object of some kind you need (e.g. linked list elements);
  • when you need to have data structures of size known only at runtime (e.g. strings based on unknown input);
  • when you know at compile time their size, but it's just too big for the stack and it would make no sense to make such thing global (e.g. big vectors to manipulate);
  • when you need to have an object whose lifetime is different than what automatic variables, which are scope-bound (=>are destroyed when the execution exits from the scope in which they are declared), can have (e.g. data that must be shared between different objects with different lifetimes and deleted when no one uses it anymore).

Notice that it isn't completely impossible to do without dynamic memory allocation (e.g. the whole rockbox project works almost without it), but there are cases in which you actually need to emulate it by using a big static buffer and writing your own allocator.

By the way, in C++ you will never use malloc()/free(), but the operators new and delete.


Related: a case in which trying to work without malloc has proven to be a big mess.

Matteo Italia
`+1` from me for an exhaustive list. Note that the question didn't have a `C++` tag, which is why I removed "C++" from its title.
sbi
Thank you; for the C++ thing, I wrote that since C++ was mentioned somewhere in the question, however it doesn't change much.
Matteo Italia
+1, You need the custom allocator/memory manager anyway to avoid fragmentation if you use it on static buffer or system buffer. correct me if I am wrong?
yadab
Yes, AFAIK you should write something that does exactly the same work that the system/CRT allocator do on the heap. So, why don't just use them? :)
Matteo Italia
In c++ it is still sometimes appropriate to use malloc and free - new has different alignment restrictions to malloc for one and malloc'd buffers can be realloc'd.
Chris Becke
AFAIK `new` is required to provide memory aligned correctly for the type you're asking, so it should be able to allocate memory aligned for any type (and if you want unaligned memory, just ask for an array of `char`). However, yes, memory allocated with `new` cannot be reallocated.
Matteo Italia
@matteo Italia The problem is that malloc() is not a part of an OS, it is a function from C runtime library declared in <stdlib.h> and <malloc.h>. It does not check for free memory holes, and does not defragment allocated memory. I do not know If C++ on windows does it either, but for BSD and Vxworks, AFAIK, we have to provide a scheme to stop fragmentation. correct me, if i am wrong.
yadab
@Chris: It's never appropriate to use `malloc()` in C++: http://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new, http://stackoverflow.com/questions/2840940/is-it-secure-to-use-malloc
sbi
@yadab: AFAIK avoiding memory fragmentation is one of the responsibilities of the allocator (so `malloc`/whatever OS function it internally calls should deal with it); in particular situations for performance reasons it may be needed to write your own allocator (if you use memory in particular patterns, etc.), but in general `malloc` should suffice.
Matteo Italia
@matteo-italia: In general, yes, you are right. But for server class application you need garbage collection library or have tight memory allocation scheme.
yadab
@yadab: yes, I can imagine that. Having just started to work on microcontrollers now I'm experiencing how memory can be a scarce resource :)
Matteo Italia
A: 

Besides the fact that your char[] method cannot resize or determine the size at runtime, your array might not be properly aligned for the type of structure you want to use it for. This can result in undefined behaviour.

schot
Really? I think, that sizeof() returns not the added size of struct's members, but the size it really takes, or you won't be able to do `malloc(sizeof())` (which is, taken from the view of memory alignment, the same as buffer on stack. -1.
Yossarian
@Yossarian: You're thinking about padding (caused by alignment requirements of members). I mean the alignment requirements of the `struct` as a total.
schot
+3  A: 

You will use malloc to dynamically allocate memory, either because:

  • you don't know at compile-time how much memory will be required,
  • you want to be able to reallocate memory later on (for instance using realloc),
  • you want to be able to discard the allocated memory earlier than by waiting for its release based on the scope of your variable.

I can see your point. You could think you could always using a declarative syntax for all of these, even using variables to declare the size of your memory spaces, but that would:

  • be non-standard,
  • give you less control,
  • possibly use more memory as you will need to do copies instead of re-allocating.

You will probably get to understand this in time, don't worry.

Also, you should try to learn more about the memory model. You don't use the same memory spaces when using a dynamic allocation and when using a static allocation.

For first pointers, visit:


Friendly advice: I don't know if you develop C on *NIX or Windows, but in any case if you use gcc, I recommend using the following compilation flags when you teach your self:

  -Wall -ansi -pedantic -Wstrict-prototypes
haylem
+1  A: 

malloc is a dynamic memory allocator which helps u up to assign memory to ur variables according to ur need and therefore reduces the loss of memory.It is also supported by realloc() function through which u can edit the memory required which u have defined earlier through malloc() or calloc(). So in short we can say that malloc() can be used for managing the memory space and making use of the necessary memory without wasting it.

Prateek
+1  A: 

You never should do this the way you are proposing. Others already told you about the difference of allocating storage on the heap versus allocation on the function stack. But if and when you are allocating on the stack you should just declare your variable:

structure A = { /* initialize correctly */ };

There is no sense or point in doing that as an (basically) untyped char array. If you also need the address of that beast, well, take the address of with &A.

Jens Gustedt
A: 

if u use char[sizeof(structure)] instead of malloc, then i think no dynamic memory allocation is done.

alfesani