一个编码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可能会产生奇奇怪怪的问题。

相关推荐
Terra.K几秒前
高精度阶乘求和模板深度解析
开发语言·c++·算法
Peregrine91 小时前
C++ - > 类和对象
java·c++·算法
Gigavision2 小时前
DEAP数据集 2026最新Transformer算法 DEAP 数据集 下载
深度学习·算法·transformer
夜之眷属2 小时前
PriorityQueue:for-each 遍历和 poll 取出,顺序一样吗?
java·服务器·数据结构·后端·算法
地平线开发者3 小时前
不是线程越多越快:用 hrt_model_exec 在 征程6M 上给 YOLOv5x 建立性能基线
算法
姜鱼问生3 小时前
fail2ban 实战:从默认配置到生产可用
后端·算法·架构
垆边人似月.3 小时前
华为题:全排列
算法·深度优先·图论
杜 硕4 小时前
快速排序详解01
数据结构·算法·排序算法
Matlab程序猿4 小时前
【MATLAB源码-第459期】基于matlab的D-H模型与阻尼最小二乘逆运动学的六自由度机械臂五次轨迹规划及动力学前馈PD控制仿真。
人工智能·算法·matlab·d-h建模·六自由度串联机械臂
信奥卷王4 小时前
[GESP202606 六级] 满二叉树
数据结构·算法