You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac与Linux下C++构造函数数组内存分配差异问题

问题描述

我正在实现一个类,其成员指针会在构造时指向一个T类型数组。该数组的初始化与置零操作在Linux机器上运行正常,但在M1系列Mac上运行相同代码时,数组指针会被移至页面对齐的内存位置。

使用的编译器分别为:Linux下的g++,Mac下的clang。

成员变量与构造函数

T* data;
int size;
int count;
int index;

cyclic_array(int size): len{ size }, count{ 0 }, index{ 0 }{
    data = new T[len];    

    for( int i = 0; i < len; i++ ) {
        data[i] = 0;
        printf("%p -> %d\n", &data[i], data[i]);
    }
    
}

注:代码中构造函数初始化列表使用len,但成员变量定义为size,此处应为笔误。

插入操作

void insert( T&& x ) {
    if( count + 1 > len ){ printf("Need to resize\n"); }
    data[ (index + count) % len ] = x;
    count++;
}

删除操作

void remove() {
    data[ index ] = 0;
    index = (index%len) + 1;
    count--;
}

打印操作

void print() {
    for( int i = 0; i < len; i++ ){
        printf("\n%p -> %d\n", &data[i], data[i]);
    }
    printf("\n\n");
}

主函数

int main() {
    cyclic_array<int> ca(4);
    char selection;

    while( selection != 'q' ) {
        printf("Menu Option [ Add ( a ), Remove ( r ), Quit ( any ) ]: ");
        scanf("%s", &selection);
        if( selection == 'a' ){
            int x {0};
            scanf("%d", &x);
            printf("x: %p\n", &x);
            ca.insert( std::move(x) );
            ca.print();
            continue;
        }
        else if( selection == 'r' ){
            ca.remove();
            ca.print();
            continue;
        }
        else
            exit(0);
    }
}

输出结果

为了验证,我打印了数组每个索引的地址,后跟->以及该地址的解引用值(应为0)。我知道模板类型不一定需要初始化为0,但为了简化选择了int作为模板类型。

输出中的地址仅作参考。

Linux环境

0x5592837e5eb0 -> 0
0x5592837e5eb4 -> 0
0x5592837e5eb8 -> 0
0x5592837e5ebc -> 0

-- Insert Value --

0x5592837e5eb0 -> 69
0x5592837e5eb4 -> 0
0x5592837e5eb8 -> 0
0x5592837e5ebc -> 0

Mac环境

0x5592837e5040 -> 0
0x5592837e5044 -> 0
0x5592837e5048 -> 0
0x5592837e504c -> 0

-- Insert Value --

0x5592837e5000 -> 69
0x5592837e5004 -> 0
0x5592837e5008 -> 275632
0x5592837e500c -> 1928562

两个环境下的标准输入均为:

a
69
q

内容的提问来源于stack exchange,提问作者robert strickland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:45:48