-
malloc and realloc
hello,
Code:
char *str;
str = (char *) malloc (sizeof (char) * strlen("hello"));
strcpy(str, "hello");
str = (char *) malloc (sizeof (char) * strlen("bye bye"));
strcpy(str, "bye bye");
g_free(str);
is the above code memory OK or the continuous allocation of malloc will lead to a memory leak problem (imagine i have a big loop of reading strings)? in other words is the use of malloc correct or do i need to use realloc? as i think the only difference between the two is that malloc is destructive without copying the previous contents while realloc is also destructive but copies the old contents if necessary
cheers
-
You have a buffer overflow in your code by the way. It should read
Code:
str = (char *) malloc (sizeof (char) * (strlen("hello")+1));
instead of
Code:
str = (char *) malloc (sizeof (char) * strlen("hello"));
It's because strlen does not count the leading '\0' character, so you're not allocating space for it. If you try to printf str later, you'll continue to print garbage until a NUL character is encountered in memory.
-
As for your question, you do have a memory leak. Either free the memory pointed to by str before mallocing more memory or use realloc.
-
Oh, and stop typecasting malloc. As with all functions that return void pointers, you don't ever typecast their return values. There's information on the FAQ as why not to do this. If it gives you a warning when you don't typecast, then stop compling as C++ and compile as C.
Quzah.