views:

207

answers:

5

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?

A: 

One reason when it is necessary to allocate the memory is if you want to modify it at runtime. In that case, a malloc or a buffer on the stack can be used. The simple example of assigning "Hello World" to a pointer defines memory that "typically" cannot be modified at runtime.

Mark Wilkins
+2  A: 

For that exact example, malloc is of little use.

The primary reason malloc is needed is when you have data that must have a lifetime that is different from code scope. Your code calls malloc in one routine, stores the pointer somewhere and eventually calls free in a different routine.

A secondary reason is that C has no way of knowing whether there is enough space left on the stack for an allocation. If your code needs to be 100% robust, it is safer to use malloc because then your code can know the allocation failed and handle it.

R Samuel Klatchko
Memory life cycles, and the related question of when and how to deallocate it, are an important issue with many common libraries and software components. They typically have a well-documented rule: "If you pass a pointer to *this* one of my routines, you need to have malloc'd it. I'll keep track of it, and free it when I'm done with it."A common source of nasty bugs is to pass a pointer to statically allocated memory to such a library. When the library tries to free() it, the program crashes. I recently spent a lot of time fixing a bug like that which someone else wrote.
Bob Murphy
+2  A: 
char *some_memory = "Hello World";
sprintf(some_memory, "Goodbye...");

is illegal, string literals are const.

This will allocate a 12-byte char array on the stack or globally (depending on where it's declared).

char some_memory[] = "Hello World";

If you want to leave room for further manipulation, you can specify that the array should be sized larger. (Please don't put 1MB on the stack, though.)

#define LINE_LEN 80

char some_memory[LINE_LEN] = "Hello World";
strcpy(some_memory, "Goodbye, sad world...");
printf("%s\n", some_memory);
ephemient
A: 

malloc is a wonderful tool for allocating, reallocating and freeing memory at runtime, compared to static declarations like your hello world example, which are processed at compile-time and thus cannot be changed in size.

Malloc is therefore always useful when you deal with arbitrary sized data, like reading file contents or dealing with sockets and your not aware of the length of the data to process.

Of course, in a trivial example like the one you gave, malloc is not the magical "right tool for the right job", but for more complex cases ( creating an arbitrary sized array at runtime for example ), it is the only way to go.

moritz
+4  A: 
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"

codaddict
Just to clarify, as much as I like this answer (I did give you +1), you can do the same without malloc() by just using a character array. Something like: char some_memory[] = "Hello"; some_memory[0] = 'W'; will also work.
randombits
Your are right. You can do that. When you use malloc() the memory is dynamically allocated at run time, so you need not fix array size at compile time also u can make it grow or shrink using realloc() None of these things can be done when you do: char some_memory[] = "Hello"; Here even though you can change the content of the array, its size is fixed. So depending on your needs you use either of the three options: 1)pointer to char const 2) dynamically allocated array 3)fixed size, compile time allocated array.
codaddict
To emphasize it's read-only you should write `const char *s = "hi";`Isn't this actually required by the standard?
Till Theis