2

From my understanding of C it seems that you are supposed to use malloc(size) whenever you are trying to initialize, for instance, an array whose size you do not know of until runtime.

But I was wondering why the function malloc() returns a pointer to the location of the variable and why you even need that.

Basically, why doesn't C just hide it all from you, so that whenever you do something like this:

    // 'n' gets stdin'ed from the user
    ...
    int someArray[n];

    for(int i = 0; i < n; i++)
        someArray[i] = 5;

you can do it without ever having to call malloc() or some other function? Do other languages do it like this (by hiding the memory properties/location altogether)? I feel that as a beginner this whole process of dealing with the memory locations of variables you use just confuse programmers (and since other languages don't use it, C seems to make a simple initialization process such as this overly complicated)...

Basically, what I'm trying to ask is why malloc() is even necessary, because why the language doesn't take care of all that for you internally without the programmer having to be concerned about or having to see memory. Thanks

*edit: Ok, maybe there are some versions of C that I'm not aware of that allows you to forgo the use of malloc() but let's try to ignore that for now...

3
  • Is your question about VLA or about dynamic allocation on heap? Commented Oct 13, 2011 at 18:59
  • 3
    Re your edit: the version that allows this is the current standard C. Ignoring it doesn't really make sense. Commented Oct 13, 2011 at 19:03
  • VLAs don't let you forgo the use of malloc(). They can do some of what malloc() can do, but by no means all. See my answer below. Commented Oct 13, 2011 at 20:09

9 Answers 9

8

C lets you manage every little bit of your program. You can manage when memory gets allocated; you can manage when it gets deallocated; you can manage how to grow a small allocation, etc.

If you prefer not to manage that and let the compiler do it for you, use another language.

Sign up to request clarification or add additional context in comments.

4 Comments

Thx, pmg. But when you deallocate, I know that you use free() but that doesn't necessarily shrink the heap. But are there cases where the heap can become shrunk (and thus the brk mark recedes)? ex. say that you free the block that was located at the highest address in the heap compared to any other block
Yes and no. I mean: unless you're writing a compiler / library for C, what happens to the available free or recently freed memory is not your concern. If you're writing a standard library in C, you don't have the luxury of using malloc and friends in the first place.
Well, actually I was wondering if it's possible to shrink the heap when the last block in the heap is free/unallocated... would you just move the brk pointer? (I'm curious if this is all that is needed to "return the memory" back to the system...)
@Dark: it's actually far more complicated than that -- depending upon the size of the allocation and the implementation of your malloc(3) routine, the memory might be allocated from an anonymous memory mapping (mmap(2), MAP_ANONYMOUS) which is far easier to give back to the operating system when free(3) is called: simply munmap(2) the region once all objects on it are free. I don't think many (any?) malloc(3) implementations shrink brk(2)-based allocations -- it probably isn't worth the complexity.
4

Actually C99 allows this (so you're not the only one thinking of it). The feature is called VLA (VAriable Length Array).

It's legal to read an int and then have an array of that size:

int n;
fscanf("%d", &n);
int array[n];

Of course there are limitations since malloc uses the heap and VLAs use the stack (so the VLAs can't be as big as the malloced objects).

*edit: Ok, maybe there are some versions of C that I'm not aware of that allows you to forgo the use of malloc() but let's try to ignore that for now...

So we can concentrate on the flame ?

10 Comments

Nope. VLA is just syntactic sugar for alloca, that allocates space on the stack, and not on the heap.
@ruslik That's true. But for small arrays that's not a problem, don't you agree ?
Sure. It's just not clear if the question is about heap or VLA.
@ruslik I got lured by the example the OP posted: int someArray[n];.
@Als That's why we love C :) If the allocation and deallocation is hidden from the programmer then you have to use garbage collector, and that's Java.
|
4

Basically, what I'm trying to ask is why malloc() is even necessary, because why the language doesn't take care of all that for you internally without the programmer having to be concerned about or having to see memory.

The very point of malloc(), it's raison d'être, it's function, if you will, is to allocate a block of memory. The way we refer to a block of memory in C is by its starting address, which is by definition a pointer.

C is close to 40 years old, and it's not nearly as "high level" as some more modern languages. Some languages, like Java, attempt to prevent mistakes and simplify programming by hiding pointers and explicit memory management from the programmer. C is not like that. Why? Because it just isn't.

2 Comments

The main difference between stack and heap is that stack is very fast, but the space is deallocated once you exit the block that allocated them (they are local). A variable on the heap can exist forever, but malloc is slow and wastes more space. That's why C allows you to choose the type of storage.
Java only uses pointers with just implicit freeing, hence the object a = new object and that b = a references b to a, doesn't copy it
3
Basically, what I'm trying to ask is why malloc() is even necessary, because why the language doesn't take care of all that for you internally without the programmer having to be concerned about or having to see memory. Thanks

One of the hallmarks of C is its simplicity (C compilers are relatively easy to implement); one way of making a language simple is to force the programmer to do all his own memory management. Clearly, other languages do manage objects on the heap for you - Java and C# are modern examples, but the concept isn't new at all; Lisp implementations have been doing it for decades. But that convenience comes at a cost in both compiler complexity and runtime performance.

The Java/C# approach helps eliminate whole classes of memory-management bugs endemic to C (memory leaks, invalid pointer dereferences, etc.). By the same token, C provides a level of control over memory management that allows the programmer to achieve high levels of performance that would be difficult (not impossible) to match in other languages.

1 Comment

Thanks for the answer, John. I guess an extended question would be, what sort of benefit does the control give to the actual C programmer himself? (as opposed to just runtime performance)
2

If the only purpose of dynamic allocation were to allocate variable-length arrays, then malloc() might not be necessary. (But note that malloc() was around long before variable-length arrays were added to the language.)

But the size of a VLA is fixed (at run time) when the object is created. It can't be resized, and it's deallocated only when you leave the scope in which it's declared. (And VLAs, unlike malloc(), don't have a mechanism for reporting allocation failures.)

malloc() gives you a lot more flexibility.

Consider creating a linked list. Each node is a structure, containing some data and a pointer to the next node in the list. You might know the size of each node in advance, but you don't know how many nodes to allocate. For example, you might read lines from a text file, creating and appending a new node for each line.

You can also use malloc() along with realloc() to create a buffer (say, an array of unsigned char) whose size can be changed after you created it.

Yes, there are languages that don't expose pointers, and that handle memory management for you.

A lot of them are implemented in C.

Comments

1

Maybe the question should be "why do you need something like int array[n] when you can use pointers?"

After all, pointers allow you to keep an object alive beyond the scope it was created in, you can use pointer to slice and dice arrays (for example strchr() returns a pointer to a string), pointers are light-weight objects, so it's cheap to pass them to functions and return them from functions, etc.

But the real answer is "that's how it is". Other options are possible, and the proof is that there are other languages that do other things (and even C99 allows different things).

Comments

1

C is treated as highly developed low-level language, basically malloc is used in dynamic arrays which is a key component in stack & queue. for other languages that hides the pointer part from the developer are not well capable of doing hardware related programming.

Comments

1

The short answer to your question is to ponder this question: What if you also need to control exactly when the memory is de-allocated?

2 Comments

Why not let a garbage collector do that, even if the gc can't deallocate exactly at the moment the memory is no longer needed?
You can, some languages do, and for some applications, that's the optimal solution.
0

C is a compiled language, not an interpreted one. If you don't know n at compile time, how is the compiler supposed to produce a binary?

5 Comments

The same way it produces a binary when malloc(n) is called?
True actually :) But still, I think the question is not about how to do it but about why memory management is left to the programmer in the first place.
That doesn't make your answer useful either ;)
Thanks, delnan. So it seems that my question seems longer than necessary, lol. Maybe I should've just asked it in a single line, such as, "Why does the programmer really need to know anything other than the value he is manipulating?" Lol.
or "Why does the programmer really need to know anything other than the actual value(variable) he is manipulating?"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.