1

I just wanted to ask if there would be a need to use malloc() for values like int or bool in C. While it sounds stupid I just wanted to get a deeper insight into C. I have seen great uses of malloc() already and have figured out that malloc() allows for easy reallocation of arrays if needed.

Would anyone mind telling me if there is a need for using malloc() if arrays or structures aren't involved?

unwind
  • 391,730
  • 64
  • 469
  • 606
Maciej Musialek
  • 56
  • 1
  • 14
  • You might want to read about heap memory and stack memory. – Abhineet Dec 09 '13 at 12:43
  • malloc() allows for easy reallocation of arrays if the exception is thrown??? – Abhineet Dec 09 '13 at 12:45
  • 2
    @Abhineet C99 introduced `bool` in ``. – unwind Dec 09 '13 at 12:45
  • @Abhineet he means "In C is very limited what you can't do". LOL – Adriano Repetti Dec 09 '13 at 12:46
  • @unwind - Got that :-) – Abhineet Dec 09 '13 at 12:46
  • Tha fact that you can use malloc on a primitive data type does not mean that actually makes much sense. You can also write statements lile 'i= i++ + ++i ;', which is valid C but very useful- – Jabberwocky Dec 09 '13 at 12:47
  • Im just beginning with C hence the question might be structured very badly. As for the actual ADT's I have excluded such. I was asking about primitive data types. I have done a bit of reading on heap memory and stack memory but I still haven't grasped the content fully. What is stopping me in my progression in C, is my understanding of allocating memory which I really want to get over. – Maciej Musialek Dec 09 '13 at 12:49
  • @Gempio - Lets' say that you get a string of unknown length at run-time. Now what would you do, if I would ask you to use memory for the string but exactly to the length of that string (+1 for '\0') ? How would you accomplish that? – Abhineet Dec 09 '13 at 12:50
  • Check this link on how the variables are stored in memory http://stackoverflow.com/a/18479996/1814023 –  Dec 09 '13 at 12:54
  • http://www-ee.eng.hawaii.edu/~dyun/ee160/Book/chap14/subsection2.1.1.8.html – Abhineet Dec 09 '13 at 12:54
  • The web is flooded with these information. And seriously, your question is too vast to explain here and moreover, its reading only which can help you to understand that. – Abhineet Dec 09 '13 at 12:56
  • I would use malloc to get me a pointer with an allocated memory for this specific purpose creating a "virtual" array. Same with the input of ints but this is very much like using an array. My problem now is, how would you know the length of an assigned pointer? Seems like using the pointer with allocated memory is a final stop in using such methods. – Maciej Musialek Dec 09 '13 at 12:56
  • @MichaelWalz You mean 'not very useful' :-) Also, the result is undefined! – pauluss86 Dec 09 '13 at 13:05
  • @pauluss86: correct, I should have written "not very useful" or even "not useful at all". – Jabberwocky Dec 09 '13 at 13:08

4 Answers4

3

No. There's no real reason to dynamically allocate a single primitive-typed variable. Apart from the conventional wisdom that heap allocation ought to be avoided unless necessary, the simplest reason to not do this is as follows.

  • Primitive types have constant size. Thus dynamically resizing makes no sense in this case.
  • Using a pointer to pass a primitive-typed variable to some function does not provide an advantage over pass-by-value.
pauluss86
  • 454
  • 6
  • 9
  • You're totally not thinking about concurrency i.e. threads – Paul Evans Dec 09 '13 at 13:00
  • I work almost exclusively with C++11 and, in any case, never used threading in combination with C. Your comment made me curious, please explain the 'issue' with regard to threads. – pauluss86 Dec 09 '13 at 13:03
  • I think he means that if you will be sharing the information of a POD type between threads, allocating it on the heap is often what you want. – Andrey Mishchenko Dec 09 '13 at 13:07
  • What if two or more threads need to share an `int`, to count something, say? I'd `malloc` that `int` and pass the pointer to all the threads. – Paul Evans Dec 09 '13 at 13:07
  • I would give each thread its own counter and sum them after they are done counting. – pauluss86 Dec 09 '13 at 13:07
  • What if you want to look at the counting in real-time, i.e. as it's happening? – Paul Evans Dec 09 '13 at 13:09
  • @PaulEvans : If you malloc the int, where are you keeping the pointer? I'd store the int where you put the pointer, and pass the address of that int. – Roddy Dec 09 '13 at 13:11
  • The pointer is passed to threads when they are created. See above comments. And the pointer *is* the address. – Paul Evans Dec 09 '13 at 13:13
  • @PaulEvans, so who frees it? – Roddy Dec 09 '13 at 13:13
  • A manager thread. i.e. the `main` thread – Paul Evans Dec 09 '13 at 13:13
  • 1
    @PaulEvans, So a manager thread is holding a pointer. Why can't it just hold the `int`? – Roddy Dec 09 '13 at 13:14
  • @PaulEvans In that case you could use a global int and put a mutex around it. – pauluss86 Dec 09 '13 at 13:14
  • 1
    @pauluss86 - Don't forget to allocate the mutex off the heap too. Oh, wait... ;-) – Roddy Dec 09 '13 at 13:15
  • Yes, you can do these things but you can also use `malloc` and without going on and on about it, there are legitimate reasons for doing so, like it may be an embedded system where you *have * to do that way. – Paul Evans Dec 09 '13 at 13:17
  • 1
    I think my answer covers that nicely with 'ought to be avoided unless necessary' :-) – pauluss86 Dec 09 '13 at 13:20
  • So you're saying there's no need for it unless there is a need for it? Yes, that's very true ;-) – Paul Evans Dec 09 '13 at 13:26
  • My logic is infallible :-) I think I meant 'there's no need for it unless you are violently being forced to do so at gunpoint'. – pauluss86 Dec 09 '13 at 13:29
2

The two primary uses of dynamic memory allocation are this:-

a: You need more memory than may be available on your stack. (For instance, a large memory buffer). In this case, you'd never be malloc-ing something as small as an int or a bool.

b: You need some memory that must persist beyond the scope of your function. In this case, you're going to have to hold a pointer to the object you've allocated. If the pointer is no smaller than the object, there's no valid reason to use heap memory for this.

However, malloc() is still frequently used to allocate such small amounts of memory, in cases when the size is not known at compile time - such as dynamically allocated character strings.

Summary:- Yes, you can write

int *c= malloc(sizeof(int));

But I've never seen a valid case for doing it.

Roddy
  • 66,617
  • 42
  • 165
  • 277
1

First of all, some insight on Stack And Heap Memory,

STACK::

When a program begins executing in the function main(), space is allocated on the stack for all variables declared within main(). If main() calls a function, additional storage is allocated for the variables in that function at the top of the stack. Notice that the parameters passed by main() to a function are also stored on the stack. When the function returns, storage for its local variables is deallocated. The memory allocated in the stack area is used and reused during program execution. It should be clear that memory allocated in this area will contain garbage values left over from previous usage.

HEAP::

We can make our program more flexible if, during execution, it could allocate additional memory when needed and free memory when not needed. Allocation of memory during execution is called dynamic memory allocation. C provides library functions to allocate and free memory dynamically during program execution. Dynamic memory is allocated on the heap by the system.

Now, let's assume that you have to read a file, say 'abc.txt', but you don't know the size of file. The file can be just 1KB or it can be 10KB. So, it would not be good if you would make an array of char of size, let's say, 10*1024 bytes, because, when the file size would be just 1KB, you are just wasting the remaining amount of memory. So, in situations like these (and many other), you should be using malloc after getting the size of file at run-time and you would free the memory after using it. Thus, optimized code using less amount of memory.

I just wanted to ask if there would be a need to use malloc() for values like int or bool in C.

No, there is no need though you can use. When a variable is defined in the source program, the type of the variable determines how much memory the compiler allocates. When the program executes, the variable consumes this amount of memory regardless of whether the program actually uses the memory allocated. This is particularly true for arrays and other primitive data types.

Abhineet
  • 5,320
  • 1
  • 25
  • 43
0

malloc can allow pointers to primitives to remain valid after the block that declared them ends. Consider the following two function in a file with a global int pointer g_var:

int* g_var;

void foo( ) {
       int stackVar = 10;

       g_var = &stackVar;
}

void bar( ) {
    int* heapVar = malloc(sizeof(int));

    *heapVar = 10;
    g_var = heapVar;
}

After foo ends stackVar ceases to exist. The value of *g_var would be undefined, it could point to any value and changing the value it points to may cause undefined behaviour or crash the program. By contrast, when bar ends g_var still point to the allocated memory: *g_var would equal 10 as expected and would be changed without causing problems.

That said, you should avoid doing something like this. It's best to avoid the heap when you can do something with the just the stack. In this example g_var should probably just be a global int rather than an int pointer and had the function change it accordingly.

  • Don't do this! It's absolutely unclear what happens in foo() or bar(). – pauluss86 Dec 09 '13 at 12:56
  • I don't think, this is the correct solution. – Abhineet Dec 09 '13 at 12:58
  • Your edit was within seconds of my comment, so all is well :-) If you absolutely need functionality like this one may pass pointer to a stack allocated int as a function argument (an 'out' parameter). – pauluss86 Dec 09 '13 at 12:59
  • I added clarification that this is a bad idea. This obviously isn't something you should do, but it answers the question of what using malloc with a primitive allows. – Benjamin Sergent Dec 09 '13 at 13:00
  • You should use foo, but with `static int stackVar = 10;`. *NEVER* use something like `bar` – Roddy Dec 09 '13 at 13:03