我已经设置了一个Kaa服务器,并使用SDK开发了一个应用程序。但是应用程序不发送事件消息。此应用程序应将进入停车场的车辆的车牌发送到服务器,并将事件发送到另一个应用程序(接收程序)。应用程序向服务器发送数据,但不发送事件。
有什么问题吗?
这是我的密码:
static void callback(void *context)
{
kaa_string_t plate;
kaa_user_log_record_t *log_record = kaa_logging_data_collection_create();
plate.data = "some license plate";
log_record->plate = &plate;
kaa_logging_add_record(kaa_client_get_context(context)->log_collector, log_record, NULL);
printf("%s uploaded\n", plate.data);
kaa_plate_detection_event_plate_event_t *plate_event = kaa_plate_detection_event_plate_event_create();
plate_event->plate = &plate;
kaa_error_t error_code = kaa_event_manager_send_kaa_plate_detection_event_plate_event(
kaa_client_get_context(context)->event_manager, plate_event, NULL);
//plate_event->destroy(plate_event);
printf("%s event sent\n", plate.data);
}发布于 2017-06-29 05:07:15
问题描述
在callback()的开头,您定义了kaa_string_t plate; ==>,这意味着它的内存在堆栈上分配。
在同一范围的后面,您将创建一个指向plate_event的指针,它将用作要发送的事件的参数。
在发送事件之前,您要分配plate_event->plate = &plate。这意味着plate_event->plate现在指向堆栈上的地址。
然后,(根据您在注释中所写的内容),您将使用异步函数发送事件。这意味着正在执行此函数的线程没有等待消息被真正发送--这就是异步函数的意思。其他的东西(可能是不同的线程,取决于send_event函数的实现)将负责发送。因此,不能保证消息是在执行下一行代码之前发送的。
在您的例子中,很可能在发送消息之前,callback()的范围结束了。因此,从现在起,这个作用域的内存将自动释放并无效,包括kaa_string_t plate。然后,在某个时候,异步发送正在执行,但它依赖于无效的内存,因为现在plate_event->plate是指向已释放的内存的。
可能解决办法
而不是在堆栈上分配kaa_string_t plate,而是在堆(malloc)上分配它。然后,当您确定消息已经发送时,内存才会有效,直到您自己释放它。
就像这样:
kaa_string_t *plate = malloc(sizeof(kaa_string_t));
strncpy(plate, "some license plate", sizeof(kaa_string_t));
...
// Now it's safe to do this:
plate_event->plate = plate;
// Sending event code
...https://stackoverflow.com/questions/44696767
复制相似问题