在嵌入式C动态内存分配 [英] Dynamic memory allocation in embedded C

查看:161
本文介绍了在嵌入式C动态内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用函数malloc和嵌入式C删除吗?例如,我有一个功能,在创建的指针在结构函数malloc。在RAM中,这个函数的返回地址,我可以利用这一点。从我的功能,其中分配内存,这个指针将被删除或此内存为这个保留的,退出后虽然没有将功能删除终止?

  typedef结构{
  字符瓦拉;
  字符varB
} MYSTRUCT;虚空MYFUNC(无效)
{
  MYSTRUCT * ptrStruct =(MYSTRUCT *)malloc的(的sizeof(MYSTRUCT));
  // code在这里
  // ........  返回;
}


解决方案

是的,你可以用malloc在嵌入式C.有些嵌入式系统有其自己的封装的内存分配的API。 malloc()函数是C LIB API。

的内存是从堆,由系统设计者定义专用的内存范围分配。如果没有你的函数退出后释放分配的内存中,分配的内存被保留,并且其他进程无法使用它。通常情况下,它是内存泄漏。如果您释放已分配的内存,但你仍然使用指针之​​后,它是一个野指针,将导致未知的行为。

Can I use functions malloc and delete in embedded C? For example, I have one function, where was created pointer on structure with function malloc. This function return address in ram and I can use this . After exit from my function, where memory was allocated, this pointer will be deleted or this memory reserved for this, while not will be function delete terminated ?

Typedef struct {
  Char varA;
  Char varB 
} myStruct ;

Void myfunc ( void) 
{
  myStruct * ptrStruct = ( myStruct *) malloc ( sizeof (myStruct)) ;
  // Code here 
  //........

  return ;    
}

解决方案

Yes, you can use malloc in embedded C. Some embedded systems have its own encapsulated memory allocation APIs. malloc() is the C lib API.

The memory is allocated from heap, a dedicated memory range defined by system designer. If you did not free the allocated memory after your function exits, the allocated memory is reserved and other processes cannot use it. Typically, it is memory leak. If you free the allocated memory but you still use the pointer after that, it is a wild pointer and will cause unknown behaviour.

这篇关于在嵌入式C动态内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆