4

I am working on learning c. I understand that malloc() allocates a block of bytes that cannot be changed or corrupted without user request, however I find myself using it very often. To be exact, I am using malloc every time that I want to create either a struct or any of its contents that I want to reference in the future. I also do understand to free() the allocated memory when its complete.

Is my use of malloc correct?

kekkles4
  • 111
  • 9
  • 9
    Correct but overzealous if you only need a local object (i. e. one with automatic storage duration and block scope). As a rule of thumb: if you `free()` in the same function that you called `malloc()` in, then you should probably just get rid of them and statically allocate the struct/array/whatever else. –  Oct 07 '13 at 05:41
  • 2
    You don't show any code, so your question is off-topic here. Read about [memory corruption](http://en.wikipedia.org/wiki/Memory_corruption), [memory leak](http://en.wikipedia.org/wiki/Memory_leak) and use [valgrind](http://valgrind.org/) – Basile Starynkevitch Oct 07 '13 at 05:41
  • 8
    @Basile: Just because a question doesn't have code doesn't make it off-topic. – icktoofay Oct 07 '13 at 05:42
  • @icktoofay Not always, but in 99.5% of the cases. I don't think OP's question is the typical "above the average" exception. –  Oct 07 '13 at 05:46
  • One of the professional c guidelines, avoid dynamic memory like the plague i.e. at least ONLY use it when you can't get away using statically allocated one. It is only a matter of added complexity and time in your code (more features, more threads etc.) when you would make a mistake (double free, dangling pointer, leave unfreed, but not accessed memory) at some point. – fkl Oct 07 '13 at 08:48
  • While we are suggesting other options, alloca.h might still be a good choice. Getting memory at runtime on stack and still not needing to free it manually http://stackoverflow.com/questions/15639912/runtime-memory-allocation-on-stack – fkl Oct 07 '13 at 08:52

3 Answers3

2

Dynamic memory allocation (malloc and family) are there for two reasons:

  • Your data needs to persist beyond the scope that allocated it (e.g. multithreading)
  • Whatever you are allocating is too large for your stack

You should really be avoiding to allocate dynamic memory for any other reason. Automatic (stack) variables are far less prone to errors and are automatically deallocated for you at the end of the scope.

Having "corrupted memory" like you call it can only really arise from bad programming and can happen on both the stack and the heap and you should not rely on dynamic memory to provide safety from buffer overflows or other mistakes that lead to memory corruption.

There is a reason why many functions in the C standard library get a pointer to a buffer as an argument to put results in: it allows you to allocate those buffers on your stack. e.g:

 ssize_t read(int fd, void *buf, size_t count);

Also as mentioned by another answer: Your stack memory is already in the CPU cache and is thus far faster accessible.

Sergey L.
  • 21,822
  • 5
  • 49
  • 75
1

Please also consider the other types of allocation:

int foo;

outside of a block will allocate a global variable, which is alive during the whole lifetime of your process, and visible for other modules of the program.

static int foo;

outside of a block is the same but visible in the actual module only.

int foo;

inside a block is alive only while the code in the block runs, then it's destroyed.

static int foo;

inside a block is visible in the block only, but it preserves its value for the entire lifetime of the process.

I'm doing a lot of embedded C coding, and using malloc() is absolutely prohibited. And it's entirely possible. You typically need malloc() if you don't know the size of your problem at compile time. But even in some cases like that, you can replace dynamic memory allocation with other techinques like recursion, line-based processing etc, etc.

SzG
  • 12,333
  • 4
  • 28
  • 41
  • Notice that using `static` data is often incompatible with multi-threading. So it might be not a general advice. – Basile Starynkevitch Oct 07 '13 at 05:53
  • While we are suggesting other options, alloca.h might still be a good choice. Getting memory at runtime on stack and still not needing to free it manually http://stackoverflow.com/questions/15639912/runtime-memory-allocation-on-stack – fkl Oct 07 '13 at 08:51
0

It depends on what you mean by

cannot be changed or corrupted without user request

If you are referring to code - then it's usually called client, not user. And it's still unclear what do you mean by that. But that's not the point.

The point is that malloc() is one of the functions used for dynamic memory allocation. It means that you can pass an address returned by this function somewhere else and data stored there will be there until it's manually deallocated. Unlike static memory allocation which is automatically freed when it's out of the scope.

So, you probably shouldn't be using malloc() if memory allocated by it is freed in the same scope, just because it's meaningless and because static allocation is faster because it's easier for CPU to cache and it's initialized at program startup, not at runtime as heap allocated memory.

Wintermute
  • 1,501
  • 17
  • 22