我使用72 am闪存与16 am控制器。IDE : Keil uVision v5.29IDE。
我正在创建一个循环缓冲区,它是指向结构的指针。
malloc正在创建一个硬错误。守则:
/*** 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。
发布于 2020-07-21 07:28:26
您的目标系统有非常小内存。malloc()可能无法满足分配请求,但您不会测试malloc()失败。硬错误可能是由于在scbuf->st_max = size;上取消引用空指针造成的。
尝试缩小结构大小,在st_array中使用较少的条目,检查malloc()是否返回NULL,并使用任何通信方式指示此错误。您还可能需要调整堆栈大小和堆大小。
还请注意以下意见:
如果argument.
scbuf作为使用灵活数组减少该结构的内存占用的一种方法:st_array在结构的末尾移动,只为头部和实际分配的元素分配足够的空间。以下是修改后的版本:
/*** 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定义为
struct main_struct st_array[0];如果编译器也拒绝此选项,则使用1作为定义的大小。
https://stackoverflow.com/questions/63008634
复制相似问题