Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use malloc for char pointers

I'm specifically focused on when to use malloc on char pointers

char *ptr; ptr = "something"; ...code... ...code... ptr = "something else"; 

Would a malloc be in order for something as trivial as this? If yes, why? If not, then when is it necessary for char pointers?

like image 725
ZPS Avatar asked Nov 24 '09 08:11

ZPS


People also ask

Do you have to malloc a char pointer?

As was indicated by others, you don't need to use malloc just to do: const char *foo = "bar"; The reason for that is exactly that *foo is a pointer — when you initialize foo you're not creating a copy of the string, just a pointer to where "bar" lives in the data section of your executable.

When should we use malloc ()?

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.

How many bytes will malloc sizeof char * 10 allocate on a 64 bit machine?

malloc(10) allocates 10 bytes, which is enough space for 10 chars. To allocate space for 10 ints, you could call malloc(10 * sizeof(int)) . char *cp = malloc(10); int *ip = malloc(sizeof(int));


1 Answers

As was indicated by others, you don't need to use malloc just to do:

const char *foo = "bar"; 

The reason for that is exactly that *foo is a pointer — when you initialize foo you're not creating a copy of the string, just a pointer to where "bar" lives in the data section of your executable. You can copy that pointer as often as you'd like, but remember, they're always pointing back to the same single instance of that string.

So when should you use malloc? Normally you use strdup() to copy a string, which handles the malloc in the background. e.g.

const char *foo = "bar"; char *bar = strdup(foo); /* now contains a new copy of "bar" */ printf("%s\n", bar);     /* prints "bar" */ free(bar);               /* frees memory created by strdup */ 

Now, we finally get around to a case where you may want to malloc if you're using sprintf() or, more safely snprintf() which creates / formats a new string.

char *foo = malloc(sizeof(char) * 1024);        /* buffer for 1024 chars */ snprintf(foo, 1024, "%s - %s\n", "foo", "bar"); /* puts "foo - bar\n" in foo */ printf(foo);                                    /* prints "foo - bar" */ free(foo);                                      /* frees mem from malloc */ 
like image 51
scotchi Avatar answered Sep 20 '22 15:09

scotchi