小编use*_*815的帖子

是否可以使用指向第一个成员的指针自由调用?

是否可以在指向结构的第一个成员的指针上调用free(并且结构是与malloc有关的结构)?我原则上知道指针指向正确的东西......

struct s {int x;};
//in main
struct s* test;
test = (struct s*) malloc(sizeof(*test));
int* test2;
test2 = &(test->x);
free(test2); //is this okay??
Run Code Online (Sandbox Code Playgroud)

此外,如果int x用结构代替,答案会改变吗?

更新:为什么我要编写这样的代码?

struct s {int x;};
struct sx1 {struct s test; int y;}; //extending struct s
struct sx2 {struct s test; int z;}; //another
// ** some functions to keep track of the number of references to each variable of type struct s 
int release(struct s* ptr){
  //if the number of references to …
Run Code Online (Sandbox Code Playgroud)

c malloc free struct padding

11
推荐指数
2
解决办法
158
查看次数

标签 统计

c ×1

free ×1

malloc ×1

padding ×1

struct ×1