Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use malloc in C and when don't I?

I understand how malloc() works. My question is, I'll see things like this:

#define A_MEGABYTE (1024 * 1024)  char *some_memory; size_t size_to_allocate = A_MEGABYTE; some_memory = (char *)malloc(size_to_allocate); sprintf(some_memory, "Hello World"); printf("%s\n", some_memory); free(some_memory); 

I omitted error checking for the sake of brevity. My question is, can't you just do the above by initializing a pointer to some static storage in memory? perhaps:

char *some_memory = "Hello World"; 

At what point do you actually need to allocate the memory yourself instead of declaring/initializing the values you need to retain?

like image 476
randombits Avatar asked Dec 26 '09 16:12

randombits


People also ask

When should you use malloc in C?

Malloc is used for dynamic memory allocation and is useful when you don't know the amount of memory needed during compile time. Allocating memory allows objects to exist beyond the scope of the current block.

What happens if we don't use malloc?

If there's an error, you're going to return without freeing the memory you allocated. This is a common source of memory leaks.

Should I avoid using malloc?

The primary reason for not using malloc in some particular cases is probably the fact that it employs a generic, one-size-fits-all approach to memory allocation. Other approaches, such as memory pools and slab allocation may offer benefits in the case of having well-known allocation needs.

Why should we use new instead of malloc?

malloc(): It is a C library function that can also be used in C++, while the “new” operator is specific for C++ only. Both malloc() and new are used to allocate the memory dynamically in heap. But “new” does call the constructor of a class whereas “malloc()” does not.


1 Answers

char *some_memory = "Hello World"; 

is creating a pointer to a string constant. That means the string "Hello World" will be somewhere in the read-only part of the memory and you just have a pointer to it. You can use the string as read-only. You cannot make changes to it. Example:

some_memory[0] = 'h'; 

Is asking for trouble.

On the other hand

some_memory = (char *)malloc(size_to_allocate); 

is allocating a char array ( a variable) and some_memory points to that allocated memory. Now this array is both read and write. You can now do:

some_memory[0] = 'h'; 

and the array contents change to "hello World"

like image 101
codaddict Avatar answered Oct 15 '22 17:10

codaddict