【发布时间】:2020-11-07 22:02:25
【问题描述】:
我正在开发一个处理 C 中某些网络连接的库,我的计划是让 init 函数返回一个结构,其中包含连接的所有相关数据,然后调用者将传递给任何库函数。我还希望调用者可以访问结构的内容。
这是我的初始化(库)代码
//here is the struct
typedef struct {
SSL_CTX* ctx;
SSL* ssl;
int socket;
int usingSSL;
} twitch_connection;
struct twitch_connection* twlibc_init(int usingSSL){ //returns a pointer to a struct that has to be freed
twitch_connection *temp;
temp = malloc(sizeof(twitch_connection)); //creates the address for the struct
struct sockaddr_in twitchaddr;
...
if(usingSSL == 0){
//not using SSL
temp->ctx = NULL;
temp->ssl = NULL;
}else {
//using SSL
temp->ctx = ctx; //how I assign values to the struct
temp->ssl = ssl;
}
temp->socket = twitchsock;
return temp; //returns the struct back to caller
}
这是我的演示代码
int main(){
twitch_connection* twlibc = twlibc_init(1);
printf("address of struct from main of callers code is: %p\n", twlibc);
}
但是,当我打印结构的地址时,从代码中的不同区域打印时会得到不同的结果:
address of struct from inside init function: 0x56299befd260
address of struct from main of callers code is: 0xffffffff9befd260
如果我尝试从主函数中打印结构的成员,我会遇到分段错误。
【问题讨论】:
-
已关闭,但显示的代码不完整。我们需要查看能够重现问题的确切代码。请提供minimal verifiable example。
-
您向我们展示了一些很好的代码,但您只向我们展示了有效的部分。向我们展示失败的代码。
-
警告在哪里?你在关注他们中的任何一个吗?用
-Wall -Werror编译!