我已经很多年没有用C编程了,所以这可能是一件很容易的事。当我试图读取malloc结构中的一些变量x、y、z时,在运行编译后的二进制文件时会出现分段错误。如果我取消注释行://v=point3D_initialize(v),则它按预期工作。就好像变量v没有保留分配地址一样。即使我在没有assert()的情况下调用函数,它也会出错:
typedef struct {
int x, y, z;
} point3D;
point3D *point3D_initialise(point3D *v) {
v = (point3D*)malloc(sizeof(point3D));
v->x = v->y = v->z = 0;
return v;
}
int TEST_setAndReadPoint3D(point3D *v) {
v = point3D_initialise(v);
assert(v!=NULL);
if((v->x == 0) && (v->y == 0) && (v->z == 0))
return 1;
else return 0;
}
void TEST_start() {
point3D *v;
assert(TEST_setAndReadPoint3D(v));
//v = point3D_initialise(v);
printf("x=%d y=%d z=%dn", v->x, v->y, v->z);
free(v);
}
按值将指针传递给TEST_setAndReadPoint3D(point3D *v)
,因此malloc返回值被分配给指针的副本。因此,传递给它的指针的实际值根本没有被函数TEST_setAndReadPoint3D()
更改。因为它没有被更改,所以它仍然是未初始化的,所以当你试图取消引用它时,你会得到segfault
试试这个
void point3D_initialise(point3D** v) {
*v = malloc(sizeof(point3D));
(*v)->x = (*v)->y = (*v)->z = 0;
}
void TEST_start() {
point3D *v;
point3D_initialise(&v);
/* v now has memory allocated to it */
free(v);
}