我正在使用Diab编译器为PowerPC构建应用程序。我遇到内存冲突的问题。
在header1.h
中我已经声明
...
void NullFunct_1 (int);
...
然后在NullFunct_1
中定义功能main.c
#include "header1.h"
...
void NullFunct_1 (int f)
{
return;
}
在header2.h
中我已经声明
struct tp_key
{
int a;
void (*fn_ptr)(int); // function pointer
unsigned int b;
unsigned int c;
int d;
int e;
};
在header2.c
中,按如下所示初始化数组Key
struct tp_key Key[48] = {0, &NullFunct_1, 0, 0, 0, 0};
在header3.h
中,我声明了全局变量Units
extern int Units;
在header3.c
中,我定义并初始化变量Units
int Units = 0; //Units variable can then assume the values of 0, 1000 or 10000 only.
程序已编译并链接,没有错误生成可执行文件。
生成的链接编辑器内存映射如下
input virtual
section address size file
...
.data 50036adc 00000484 header2.o
Key 50036adc 00000480
Xxxx 50036f5c 00000004
.data 50036f60 00000170 header3.o
Units 50036f60 00000004
...
...
NullFunct_1 500038b8 0000000c main.o
...
您可能会注意到变量Key
和Units
是内存“邻居” 0x50036adc + 0x480 = 0x50036f5c
。
在某些情况下,变量Units
包含与变量1342191800
的内存地址相对应的值(0x500038B8 in hex)
Null_Funct_1
这是由于指示而发生的
struct tp_key Key[48] = {0, &NullFunct_1, 0, 0, 0, 0};
这是一个链接器问题,没有正确计算变量Key的内存大小?还是我做错了?即使存在链接器问题,也可以建议如何避免此类问题吗?
这里没有“冲突”。
sizeof(struct tp_key)[24] * 48(十六进制)为0x480。因此,一切都很好100%。
[我的建议:不要专注于追求“编译器错误”。假设编译器已经过测试,并且被数百万程序员使用。
Key
有48个元素,但是在我的源代码中,我分配了变量Key [48],这当然是不正确的。代码中的错误原因是
for ( i=0; i <= 48; i++)
{
Key[i].fn_ptr = &NullFunct_1;
}
为了解决这个问题,我如下更改了for循环
for ( i=0; i < 48; i++)
{
Key[i].fn_ptr = &NullFunct_1;
}