首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >malloc -硬断层- Keil uVision

malloc -硬断层- Keil uVision
EN

Stack Overflow用户
提问于 2020-07-21 06:30:44
回答 1查看 260关注 0票数 1

我使用72 am闪存与16 am控制器。IDE : Keil uVision v5.29IDE。

我正在创建一个循环缓冲区,它是指向结构的指针。

malloc正在创建一个硬错误。守则:

代码语言:javascript
复制
/*** Header File *****/


typedef struct circular_structbuf_t circular_structbuf_t;

typedef circular_structbuf_t* scbuf_handle_t;

/****** C file *****/
struct main_struct
{
    int data;
    char char_data;
}

struct circular_structbuf_t
{
    struct  main_struct st_array[128];
    uint8_t st_head;
    uint8_t st_tail;
    uint8_t st_max; //of the buffer
    bool st_full;
};


scbuf_handle_t circular_structbuf_init(scbuf_handle_t scbuf, size_t size)
{
    scbuf = malloc(sizeof(circular_structbuf_t));                       // Causes Hardfault
    scbuf->st_max = size;
    circular_structbuf_reset(scbuf);
    return scbuf;
}


/** Main File ***/
scbuf_handle_t p_cbuf;


int main(void)
{
    p_cbuf=circular_structbuf_init(p_cbuf,50);
    
}

调试时,p_cbuf的地址被指定为0x0

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-21 07:28:26

您的目标系统有非常小内存。malloc()可能无法满足分配请求,但您不会测试malloc()失败。硬错误可能是由于在scbuf->st_max = size;上取消引用空指针造成的。

尝试缩小结构大小,在st_array中使用较少的条目,检查malloc()是否返回NULL,并使用任何通信方式指示此错误。您还可能需要调整堆栈大小和堆大小。

还请注意以下意见:

如果argument.

  • you总是分配新结构,则
  • 不应将scbuf作为使用灵活数组减少该结构的内存占用的一种方法:st_array在结构的末尾移动,只为头部和实际分配的元素分配足够的空间。

以下是修改后的版本:

代码语言:javascript
复制
/*** Header File *****/

typedef struct circular_structbuf_t circular_structbuf_t;

typedef circular_structbuf_t *scbuf_handle_t;

/****** C file *****/

struct main_struct {
    int data;
    char char_data;  // if `int` is aligned, there will be some padding after this field
};

struct circular_structbuf_t {
    uint8_t st_head;
    uint8_t st_tail;
    uint8_t st_max; // of the buffer
    bool st_full;   // type bool is assumed to be a `uint8_t`
    struct main_struct st_array[];  // flexible array syntax
};

scbuf_handle_t circular_structbuf_init(size_t size) {
    scbuf_handle_t scbuf; 
    scbuf = malloc(sizeof(circular_structbuf_t) + size * sizeof(struct main_struct));
    if (scbuf) {
        scbuf->st_max = size;       
        circular_structbuf_reset(scbuf);
    }
    return scbuf;
}

/** Main File ***/

scbuf_handle_t p_cbuf;

int main(void) {
    p_cbuf = circular_structbuf_init(50);
    if (p_cbuf == NULL) {
        /* report the error */
    }
    ...
    return 0;
}

如果编译器不支持灵活数组,则可以将st_array定义为

代码语言:javascript
复制
struct main_struct st_array[0];

如果编译器也拒绝此选项,则使用1作为定义的大小。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63008634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档