[英]Is it safe to assign a struct member pointer to another dynamically memory allocated pointer?
#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;
}
这是允许的吗? 将结构成员分配给test_new
函数中的局部变量(字符指针)? (是否允许test->str = s
?)
我听说数组变量,当它是本地的,在函数结束后被释放。 我想知道这是否适用于内存分配的局部变量。
像这样:
char *test(void) {
char s[100];
return s;
}
s
将在函数结束时消失,所以我想知道这是否适用于我的结构,尤其是我没有返回,而是更改了一个成员。
将结构成员指针(即test->str
)分配给另一个动态内存分配指针(即s
)是否安全?
从test_new
函数中,让我们看一下这两行:
// 1
char *s = malloc(100);
// 2
test->str = s;
1
之后你有这样的事情:
+---+ +-------------------------------+ | s | --> | memory allocated by malloc... | +---+ +-------------------------------+
然后在2
之后你有这样的事情:
+---+ | s | ----------\ +---+ \ +-------------------------------+ >--> | memory allocated by malloc... | +-----------+ / +-------------------------------+ | test->str | --/ +-----------+
然后一旦test_new
返回, main
函数中就只有这个:
+----------+ +-------------------------------+ | test.str | --> | memory allocated by malloc... | +----------+ +-------------------------------+
这完全没问题。
在test_new
函数中完成的分配/赋值是允许的并且是安全的。 这是因为char *s = malloc(100);
line 在堆上分配内存(不在“本地”堆栈上),并且test->str = s;
line 将指向该分配内存的指针分配给通过引用传递的结构成员。 因此,调用代码的结构变量中的该成员将按照您的意图进行修改。
有什么问题(使用第二个代码段中的本地内存示例)将是这样的:
void test_bad(Test *test) {
char s[100]; // Local memory - gone when function returns
s[0] = 'H';
s[1] = 'i';
s[2] = '\0';
test->str = s; // Pointer member of structure will be invalid after the return.
}
上面的错误代码会编译(它在语法上是正确的),但任何体面的编译器都会(或应该)警告您使用指向局部变量的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.