【发布时间】:2015-12-14 10:13:09
【问题描述】:
我在尝试初始化指向 0mq 上下文和套接字的指针结构时遇到分段错误。 main 方法中注释掉的代码有效,但它只使用局部变量。我想初始化它们并在结构中传递它们,但我的 google foo 让我无法正确执行此操作。
#include "zhelpers.h"
#include <stdio.h>
#include <stdlib.h>
#include <zmq.h>
struct publisher{
void *handle;
void *context;
};
void init_publisher(struct publisher *p);
void destroy_publisher(struct publisher *p);
void publish(struct publisher *p,char *msg);
void init_publisher(struct publisher *p)
{
p = (struct publisher *)malloc(sizeof(struct publisher));
p->context = malloc(sizeof(void *));
p->handle = malloc(sizeof(void *));
void *context = zmq_ctx_new();
void *handle = zmq_socket(context,ZMQ_PUB);
zmq_bind(handle, "tcp://*:5556");
zmq_bind(handle, "ipc://feed.ipc");
p->context = context;
p->handle = handle;
}
void destroy_publisher(struct publisher *p)
{
zmq_close(p->handle);
zmq_ctx_destroy(p->context);
free(p->handle);
free(p->context);
free(p);
}
void publish(struct publisher *p,char *msg)
{
s_send(p->handle, msg);
}
int main(void)
{
/**
void *context = zmq_ctx_new();
void *publisher = zmq_socket(context, ZMQ_PUB);
int rc = zmq_bind(publisher, "tcp://*:5556");
assert(rc == 0);
rc = zmq_bind(publisher, "ipc://weather.ipc");
assert(rc == 0);
printf("Started Weather Server...\n");
srandom((unsigned) time (NULL));
int zipcode, temperature, relhumidity;
zipcode = randof(100000);
temperature = randof (215) - 80;
relhumidity = randof (50) + 10;
char update[20];
sprintf(update, "%05d %d %d", zipcode, temperature, relhumidity);
s_send(publisher, update);
zmq_close(publisher);
zmq_ctx_destroy(context);
*/
struct publisher *p;
init_publisher(p);
printf("Setup pub\n");
srandom((unsigned) time (NULL));
int zipcode, temperature, relhumidity;
zipcode = randof(100000);
temperature = randof (215) - 80;
relhumidity = randof (50) + 10;
char update[20];
sprintf(update, "%05d %d %d", zipcode, temperature, relhumidity);
publish(p,update);
printf("Published Message\n");
destroy_publisher(p);
printf("Destroyed publisher\n");
return 0;
}
【问题讨论】:
-
避免使用 void 指针——它有一定的含义
-
p = (struct publisher *)malloc(sizeof(struct publisher));--->p = malloc(sizeof(struct publisher));一个问题是您没有检查malloc()是否没有返回NULL。另一个问题是你不知道代码到底在哪里崩溃,使用调试器。 -
@iharob 它在 zeromq 代码中崩溃。但是在这两种情况下,实际初始化 void 指针的调用是相同的。所以在我看来,我没有正确设置结构,因为如果我在 main 方法(注释掉的代码)中完成所有工作,它不会引发任何错误。
-
我建议只从您的 init_publisher 方法返回一个“struct publisher *”。如果你真的不想这样做,在这种情况下,你必须传递一个指针到指针(struct publish **p)。