Let’s say I have a struct:
typedef struct {
int number1; /* dummy */
int number2; /* dummy */
int number3; /* dummy */
char *name1;
char name2[];
} Klass;
and the rest of the code is:
int main(int argc, char const *argv[])
{
char *name1 = "this is a name"; /* 1st case */
char name2[] = "this is also a name"; /* 2nd case */
Klass k;
k.number1 = 10;
k.number2 = 20;
k.number3 = 30;
k.name1 = "this is my first name"; /* 3rd case */
/* error: invalid use of flexible array member */
k.name2 = "this is my second name";
Klass *kp = (Klass*)malloc(sizeof(Klass));
kp->number1 = 100;
kp->number2 = 200;
kp->number3 = 300;
kp->name1 = "this is also my first name"; /* 4th case */
/* error: invalid use of flexible array member */
kp->name2 = "this is my second name";
return 0;
}
- Can anyone clarify for me how the memory is allocated (heap vs stack) in the marked cases?
- How should I free memory at the end of main block?
- What’s the reason compiler is giving the
error: invalid use of flexible array member?
EDIT
If you say k.name = "this is my name"; and kp->name = "this is also my name"; is on the stack, can you explain how I can reach "this is my name" like this:
Klass *kp;
int foo() {
Klass k;
k.number1 = 10;
k.number2 = 20;
k.number3 = 30;
k.name = "this is my name";
kp = &k;
} // k is destroyed now
int main(int argc, char const *argv[])
{
kp = (Klass*)malloc(sizeof(Klass));
foo();
printf("%d\n", kp->number1); /* segfault */
printf("%d\n", kp->number2); /* segfault */
printf("%d\n", kp->number3); /* segfault */
printf("%s\n", kp->name); /* prints "this is my name" */
return 0;
}
This just allocates a pointer, setting it to point to the string (which is kept as static data).
This is short for
char name2[sizeof(init_string)] = "this is also a name";and allocates enough space to store the characters in the string.Your third case
allocates no space at all! There is nowhere to store a string (which would have had to be copied using
strcpyanyway).The 4th case
is similar to case 1 –
name1is a pointer that is set to point to a static text.