MeRock027 MeRock027 - 1 month ago 16
C Question

why sometimes it's not required to allocate memory in C?

I have seen sometimes people don't allocate memory even if they declare struct as pointer. Why is it so? For example:

struct test {
int a;
char *b;
struct _test_2 {
int d;
char *f;
} *test_2;
}


1)

struct test my_var;
my_var.a = 10;
my_var.b = "test string";
my_var.test_2->d = 20;
my_var.test_2->f = "test string2"


2)

struct test my_var;
my_var.a = 10;
my_var.b = "test string";
my_var.test_2 = (struct _test_2) malloc(sizeof(struct _test_2));
my_var.test_2->d = 20;
my_var.test_2->f = "test string2"

// free it after done
free(my_var.test_2);


What is the difference between these two? Which one is a correct way to use it?

Answer Source

One is doing proper memory management and the other is not doing it. You're just taking a risk with the first example and hoping your data doesn't get overwritten or malformed. On the second one you properly allocate memory (but you're missing a * on the internal struct allocation).

#2 would be the best choice.