【问题标题】:Is this valid memory alignment? If not, how should this be fixed?这是有效的内存对齐吗?如果不是,应该如何解决?
【发布时间】:2015-05-15 01:26:54
【问题描述】:

decNumber.h:

typedef struct {
int32_t digits;      /* Count of digits in the coefficient; >0    */
int32_t exponent;    /* Unadjusted exponent, unbiased, in         */
                     /* range: -1999999997 through 999999999      */
uint8_t bits;        /* Indicator bits (see above)                */
                     /* Coefficient, from least significant unit  */
decNumberUnit lsu[DECNUMUNITS]; // decNumberUnit is int16_t and DECNUMUNITS is 1
} decNumber;

Test.cpp:

decNumber a,b,c;

当我打印 a、b 和 c 的地址时,我得到的是:

a:0x7fff0d7a9858 到 0x7fff0d7a9864

b:0x7fff0d7a9864 到 0x7fff0d7a9870

c:0x7fff0d7a987c 到 0x7fff0d7a9888

a和b之间0x7fff0d7a9864的字节重叠是否有效?该程序最终会遇到分段错误。为什么?

非常感谢任何帮助!

【问题讨论】:

  • 如何“打印地址”? (Maybe related)
  • 真的有字节重叠吗?或者您正在打印&a + 1(char*)&a + sizeof(a) 之类的内容,这将给出a 末尾之后的地址,可以被另一个对象使用?
  • 感谢您的 cmets 迈克。我最终发现在 decnumber 库中执行了类似的操作,其中结构指针在 for 循环中递增。我们遇到 seg 错误的原因是我们没有在代码中为 decNumber 结构分配足够的空间(需要设置特定的值以具有正确的 DECNUMUNITS)。

标签: c++ memory segmentation-fault alignment


【解决方案1】:

a和b之间0x7fff0d7a9864的字节重叠是否有效?

没有字节重叠。例如,0 到 5 表示 [0, 1, 2, 3, 4],5 到 10 表示 [5, 6, 7, 8, 9]。

这个程序最终会遇到分段错误。为什么?

不可能。问题中的程序不完整,无法编译。它不会导致分段错误,因为没有可以运行的程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2018-05-04
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2023-02-06
    相关资源
    最近更新 更多