0

我在 MPLAB 上编码,使用 XC32 编译器,并试图掌握使用动态内存的窍门,所以我创建了一个基本的示例程序:

#include <stdlib.h>
#include <plib.h>

char x;
char y;



char main(void)
{
    Nop();
    char *pLocation = (char *)malloc(16);
    if(pLocation == 0x00)
    {
        return 0;
    }

    for(x = 0;x<=7;x++)
    {
        *pLocation = x;
        pLocation++;

    }
    while(1)
    {

        Nop();
    }
}

问题:

  • 当指针到达malloc调用行时,值pLocation被强制为 0x00,这意味着它以某种方式无法从堆中传递指针信息。
  • 当指针开始将值分配给指针x的位置时,pLocation我得到一个总线异常,说Unimplemented RAM memory access。我怀疑这是因为我试图写入 0x00。

我在代码中做错了吗?

附加信息:

  • 我已经分配了一个 16 字节的堆。
  • 对于偶数大小为 2 的内存请求,我得到相同的错误。
  • 我正在使用 MPLAB SIM 调试器。
  • MPLAB 版本 8.87.00.00。
  • 使用 XC32 编译器构建。
4

2 回答 2

3

我已经分配了 16 个堆

这不足以支持 16 字节的分配。堆管理需要一定量的空间,并且每个分配将保证对齐通常为 8 个字节,以确保对齐 64 位数据类型。

您应该分配比必要更多的堆,当然超过 16 个字节 - 为此您最好使用堆栈或静态分配。

Typically you would want to allocate all available memory not used for other purposes (stack-space, statics, DMA pools etc.) to the heap since it will be unused otherwise (you might allow a little headroom so that in maintenance small changes to static allocation don't require you to change the heap size) ; but you can test my hypothesis simply by increasing the heap allocation to 1024 bytes for example. If you don't have that much available, then your system really is not suited to supporting a heap at all perhaps.

于 2013-01-10T13:51:00.167 回答
0

使堆大小> = 32可以解决此问题,但我无法解释原因。它可能以某种方式与它的 32 位图片有关。

如果有人可以,我将不胜感激。

- - -编辑 - - -

我有一些进一步的信息,每次我希望对新指针进行新的 malloc 调用时,即使我没有使用全部堆,我也必须将堆增加 32。同样在地址中,这些指针由 minimim 23 分隔!即使 malloc 请求介于 1 和 8 之间,位置也会在您想要更多时进行。但是当然,如​​果您不小心,一个指针可以毫无问题地进入另一个指针的范围

于 2013-01-10T13:07:02.963 回答