运行我的代码时,我发现了一个奇怪的内存损坏。它发生在下面的块中的“cin”。有趣的是,for循环第一次运行。在第二次迭代(当i = 1时)发生了错误。
case 3:
{
// for(int i = 0; i < MAX_PLAYERS; i++)
for(int i = 0; i < 5; i++)
{
mavlink_param_value_t packet_vel, packet_pwr;
float vel_factor;
float power_factor;
strcpy(packet_vel.param_id, "GAME_VEL_FACTOR");
strcpy(packet_pwr.param_id, "GAME_PWR_FACTOR");
printf("Current index %d\n", i);
// cout << "\n" << "Enter Game Velocity Factor:";
// cin >> packet_vel.param_value;
cout << "\n" << "Enter Game Power Factor:";
cin >> power_factor;
printf("Assigning local variable to struct member\n");
packet_pwr.param_value = power_factor;
printf("Packing current message\n");
mavlink_msg_param_value_pack((uint8_t)i,
1,
&messages[i],
packet_vel.param_id,
packet_vel.param_value,
packet_vel.param_type,
1,
1);
}
*cont_mode = true;
break;
以下是错误:
Enter message for player 0
Current index 0
Enter Game Power Factor:1
Assigning local variable to struct member
Packing current message
Current index 1
Enter Game Power Factor:2
*** Error in `./send_mavlink_msgs': malloc(): memory corruption (fast): 0x0000000000ccf050 ***
Aborted (core dumped)
谢谢!
更新:
以下是我创建“消息”的方式
mavlink_message_t *messages = (mavlink_message_t *)malloc(num_of_robots*sizeof(mavlink_global_position_int_t));
找到了here
的定义答案 0 :(得分:3)
mavlink_message_t *messages = (mavlink_message_t *)
malloc(num_of_robots*sizeof(mavlink_global_position_int_t));
这应该是:
mavlink_message_t *messages = (mavlink_message_t *)
malloc(num_of_robots*sizeof(mavlink_message_t));
使用错误的sizeof
参数将分配错误的空间量。如果mavlink_global_position_int_t
小于mavlink_message_t
(从我粗略的谷歌搜索,似乎就是这种情况),这是一个严重的问题。
另外,我对[&#34; mavlink&#34;是,但从here判断:
typedef struct __mavlink_param_value_t
{
int8_t param_id[15]; ///< Onboard parameter id
float param_value; ///< Onboard parameter value
uint16_t param_count; ///< Total number of onboard parameters
uint16_t param_index; ///< Index of this onboard parameter
} mavlink_param_value_t;
param_id
是一个15字节的数组。如果您计算末尾的"GAME_VEL_FACTOR"
终结符,则"GAME_PWR_FACTOR"
和'\0'
都是16字节字符串。