一个编码BUG

如下代码执行结果是什么?

objectivec 复制代码
#include <stdio.h>
#include <string.h>

struct test_info {
        int a;
        char *name;
};

static struct test_info hhh_info[2];
static char test_name[2][8];

int main()
{
        for (int i = 0; i < 2; i++) {
                memset(&hhh_info[i], 0, sizeof(hhh_info));
                snprintf(test_name[i], sizeof(test_name[i]), "good%d", i);
                hhh_info[i].name = test_name[i];
        }

        for (int j = 0; j < 2; j++) {
                printf("hhh_info name: %s\n", hhh_info[j].name);
                printf("test_name[j] is: %s\n", test_name[j]);
        }
        printf("test_name addr is: %p\n", test_name);
        printf("hhh_info addr is: %p\n", hhh_info);

        return 0;
}

gcc编译后执行结果如下:

bash 复制代码
hhh_info name:
test_name[j] is:
hhh_info name: good1
test_name[j] is: good1
test_name addr is: 0x564026243060
hhh_info addr is: 0x564026243040

会发现hhh_info第一个元素为空,奇怪?分析下看下

首先代码bug是由于memset误将整个数组的大小传入,导致第二次循环越界。

objectivec 复制代码
memset(&hhh_info[i], 0, sizeof(struct test_info));

但是为什么会导致第一个元素为空呢?从打印的地址可以看到,test_name和hhh_info相差32字节。struct test_info大小为16字节,hhh_info大小为32字节,所以test_name在内存布局上紧挨着hhh_info,因此,第二次循环时,会将整个test_name空间情况,2x8正好为16字节大小。

稍微调整下代码实现,看下输出结果:

objectivec 复制代码
#include <stdio.h>
#include <string.h>

struct test_info {
        int a;
        char *name;
};

static char test_name[2][8];
static struct test_info hhh_info[2];

int main()
{
        for (int i = 0; i < 2; i++) {
                memset(&hhh_info[i], 0, sizeof(hhh_info));
                snprintf(test_name[i], sizeof(test_name[i]), "good%d", i);
                hhh_info[i].name = test_name[i];
        }

        for (int j = 0; j < 2; j++) {
                printf("hhh_info name: %s\n", hhh_info[j].name);
                printf("test_name[j] is: %s\n", test_name[j]);
        }
        printf("test_name addr is: %p\n", test_name);
        printf("hhh_info addr is: %p\n", hhh_info);

        return 0;
}

gcc编译后执行结果如下:

bash 复制代码
hhh_info name: good0
test_name[j] is: good0
hhh_info name: good1
test_name[j] is: good1
test_name addr is: 0x5649a73c1040
hhh_info addr is: 0x5649a73c1060

低级编码bug可能会产生奇奇怪怪的问题。

相关推荐
dialect_5 小时前
KMP算法
开发语言·c++·算法
reikocao6 小时前
卡尔曼滤波的动态机制:P如何改变融合权重
算法
漂流瓶jz6 小时前
UVA-1612 猜名次 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·题解·排序·aoapc·算法竞赛入门经典
吞下星星的少年·-·7 小时前
Div.2 CF 1130B题(构造,贪心)
算法·贪心·构造
是main不是漫8 小时前
【双指针——移动零】数组划分类题目的入门基石
c++·算法
深圳市快瞳科技有限公司9 小时前
野外鸟类AI识别落地实录:输入适配、结构化输出、去重聚合与置信度分流的工程实践
算法·计算机视觉·鸟类识别·鸟类ai识别·野外鸟类观测·林业调查
专注仿真10 小时前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法
小豆庄11 小时前
视频遮罩追踪退场后ID撞号的排查—多目标场景下的失效
opencv·算法·bug·视频·python3.11
Tisfy11 小时前
LeetCode 3882.网格图中最小异或路径:动态规划
算法·leetcode·动态规划
D e re k ZH12 小时前
P5025 [SNOI2017] 炸弹
c++·算法