I do not have a good theoretical grasp of when to use malloc(). I know what it does, but I am too new to C to really dig it. I am quite aware that a considerable number of eyes are starting to glaze over now out of sheer boredom, but I searched for it, found a lot, but nowhere a good and concise overview.
I have found one clear use for malloc(), if I want persistent results from a function that do not get cleared when I exit the function, I use malloc. The rest is kind of vague with ominous talks about memory management, safe pieces of memory and what all, conceptual clarity is lacking. So, to be clear, my question is when one should use malloc.
The example I am using is a very simple concatenation.
Malloc version (not mine):
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BEGIN "@@"
#define END "CCC"
int main (void)
{
char *result = malloc(100 * sizeof(char)); // create some string space
strcpy(result, BEGIN);
// result holds @@
strcat(result, "this is a message");
//result holds @@this is a message
strcat(result, END);
// result holds @@this is a messageCCC
printf("%s\n\n", result);
free(result);
return 0; }
The version without malloc:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BEGIN "@@"
#define END "CCC"
int main (void)
{
char *result;
strcat(result, BEGIN);
// result holds @@
strcat(result, "this is a message");
// result holds @@this is a message
strcat(result, END);
// result holds @@this is a messageCCC
printf("%s\n\n", result);
return 0; }
Both versions run well, but is this coincidence? What risks to I run if I work without malloc in this case, is this good programming or a don't?