16

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

char[sizeof(structure)]

Then when is malloc necessary?

sbi
  • 219,715
  • 46
  • 258
  • 445
wamp
  • 5,789
  • 17
  • 52
  • 82
  • Despite syntactic similarities, C and C++ are _very different_ programing languages. That's especially true when it comes to dynamic memory. You shouldn't even _use_ `malloc()` in C++. Since your question doesn't have a `C++` tag, I will remove "C++" from its title. – sbi Oct 08 '10 at 10:04
  • Won't the above memory occupied from stack and if we use malloc it will be occupied in heap?If a very large amount of memory is asked to be occupied can result in overflow as much I know..Please comment if I am wrong. –  Oct 08 '10 at 14:08

8 Answers8

27
  • 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); this is somewhat mitigated by the introduction of VLAs in C99, but see the next point:
  • when you know at compile time their size (or you can use VLAs), but it's just too big for the stack (typically a few MBs at most) 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.

Community
  • 1
  • 1
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
  • `+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 Oct 08 '10 at 10:06
  • 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 Oct 08 '10 at 10:11
  • +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 Oct 08 '10 at 11:20
  • 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 Oct 08 '10 at 11:25
  • 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 Oct 08 '10 at 13:11
  • 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 Oct 08 '10 at 13:37
  • @matteo Italia The problem is that malloc() is not a part of an OS, it is a function from C runtime library declared in and . 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 Oct 08 '10 at 14:23
  • @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 Oct 08 '10 at 16:35
  • @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 Oct 08 '10 at 18:46
  • @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 Oct 09 '10 at 04:19
  • @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 Oct 09 '10 at 09:16
9

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 yourself:

  -Wall -ansi -pedantic -Wstrict-prototypes
haylem
  • 22,460
  • 3
  • 67
  • 96
3

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
  • 29,161
  • 19
  • 114
  • 169
  • if `char buff[10]` is defined inside a function, it has automatic storage duration not static storage duration. – Van Tr Jan 04 '20 at 11:37
1

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,538
  • 13
  • 22
1

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
  • 76,821
  • 6
  • 102
  • 177
0

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
  • 74,600
  • 47
  • 176
  • 233
0

If you use char[sizeof(structure)] instead of malloc, then I think no dynamic memory allocation is done.

Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62
alfesani
  • 451
  • 2
  • 6
  • 11
-1

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
  • 10,958
  • 2
  • 46
  • 71
  • 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. – nothrow Oct 08 '10 at 10:37
  • @Yossarian: You're thinking about padding (caused by alignment requirements of members). I mean the alignment requirements of the `struct` as a total. – schot Oct 08 '10 at 10:44