#include <stdio.h>
#include <stdlib.h>
struct Test {
const char *str;
};
void test_new(Test *test) {
char *s = malloc(100);
s[0] = 'H';
s[1] = 'i';
s[2] = '\0';
test->str = s;
}
int main(void) {
struct Test test;
test_new(&test);
puts(test.str);
free(test.str);
return 0;
}
Is this allowed? Assigning a struct member to a local variable (character pointer) in the test_new
function? (Is test->str = s
allowed?)
I heard that array variables, which are local when it is, are freed after the end of the function. I wonder if that applies to memory allocated local variables.
Like this:
char *test(void) {
char s[100];
return s;
}
s
will be gone by the time the function ends, so I wonder if this applies to my struct, especially that instead of returning, I'm changing a member.
Is it safe to assign a struct member pointer (which is test->str
) to another dynamically memory allocated pointer (which is s
)?