Question

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?

Was it helpful?

Solution 3

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.

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top