json-tutorial icon indicating copy to clipboard operation
json-tutorial copied to clipboard

第三单元解析字符串 realloc 可能分配失败的问题

Open Huangtuzhi opened this issue 9 years ago • 3 comments

static void* lept_context_push(lept_context* c, size_t size) {
    void* ret;
    assert(size > 0);
    if (c->top + size >= c->size) {
        if (c->size == 0)
            c->size = LEPT_PARSE_STACK_INIT_SIZE;
        while (c->top + size >= c->size)
            c->size += c->size >> 1;  /* c->size * 1.5 */
        c->stack = (char*)realloc(c->stack, c->size);
    }
    ret = c->stack + c->top;
    c->top += size;
    return ret;
}

一旦 realloc 分配失败,返回 NULL。c->stack 赋值为 NULL,之前 c->stack 指向的内存未释放。是不是需要加一个逻辑判断内存分配是否正常。

void* new_ptr = (char*)realloc(c->stack, c->size);
if (!new_ptr) {
    // 错误处理
}
c->stack = new_ptr;

Huangtuzhi avatar Oct 11 '16 02:10 Huangtuzhi

需要

kingFighter avatar Nov 02 '17 08:11 kingFighter

确实需要判断,realloc可能会分配失败,一旦分配失败,则原来的指针会为null

hengqiali avatar Jan 06 '21 03:01 hengqiali

确实需要判断,realloc可能会分配失败,一旦分配失败,则原来的指针会为null

hengqiali avatar Jan 06 '21 03:01 hengqiali