1 Star 0 Fork 1.2K

清哥 / LiteOS

forked from Huawei LiteOS / LiteOS 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
programming-example-3.md 1.88 KB
一键复制 编辑 原始数据 按行查看 历史

Programming Example

Example Description

Prerequisite: Dynamic memory has been configured in the menuconfig menu.

In the programming example, the following steps will be performed:

  1. Initialize a dynamic memory pool.
  2. Apply for a memory block from the dynamic memory pool.
  3. Store data in the memory block.
  4. Print the data in the memory block.
  5. Free up the memory block.

Programming Example

#define TEST_POOL_SIZE (2*1024*1024)
UINT8 g_testPool[TEST_POOL_SIZE];

VOID Example_DynMem(VOID)
{
    UINT32 *mem = NULL;
    UINT32 ret;

    ret = LOS_MemInit(g_testPool, TEST_POOL_SIZE);
    if (LOS_OK  == ret) {
        dprintf("The memory pool is successfully initialized.\n");
    } else {
        dprintf("Failed to initialize the memory pool.\n");
        return;
    }

    /*Allocate memory.*/
    mem = (UINT32 *)LOS_MemAlloc(g_testPool, 4);
    if (NULL == mem) {
        dprintf("Failed to allocate memory.\n");
        return;
    }
    dprintf("Memory is successfully allocated.\n");

    /*Assign a value.*/
    *mem = 828;
    dprintf("*mem = %d\n", *mem);

    /*Free up memory.*/
    ret = LOS_MemFree(g_testPool, mem);
    if (LOS_OK == ret) {
        dprintf("Memory is successfully freed up.\n");
    } else {
        dprintf("Failed to free up memory.\n");
    }

    return;
}

Verification

The verification result is as follows:

The memory pool is successfully initialized.
Memory is successfully allocated.
*mem = 828
Memory is successfully freed up.

Complete Code

sample_mem.c

C
1
https://gitee.com/spdh/LiteOS.git
git@gitee.com:spdh/LiteOS.git
spdh
LiteOS
LiteOS
master

搜索帮助