可以memset的()与一个空指针称为如果大小为0? [英] Can memset() be called with a null pointer if the size is 0?

查看:731
本文介绍了可以memset的()与一个空指针称为如果大小为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关或那样的原因,我想用手卷的零版本的malloc()。为了尽量减少算法的复杂性,我想这样写:

For one reason or another, I want to hand-roll a zeroing version of malloc(). To minimize algorithmic complexity, I want to write:

void * my_calloc(size_t size)
{
    return memset(malloc(size), 0, size);
}

这是明确的,当尺寸== 0 ?这是罚款调用的malloc()具有零大小,但允许它返回一个空指针。将 memset的的后续调用即可,或者这是不确定的行为,我需要补充一个条件如果(大小)

Is this well-defined when size == 0? It is fine to call malloc() with a zero size, but that allows it to return a null pointer. Will the subsequent invocation of memset be OK, or is this undefined behaviour and I need to add a conditional if (size)?

我就非常希望避免冗余条件检查!

I would very much want to avoid redundant conditional checks!

假设为 malloc的时刻()不会失败。在现实中就会有一个手卷版本的malloc()出现,也将终止失败。

Assume for the moment that malloc() doesn't fail. In reality there'll be a hand-rolled version of malloc() there, too, which will terminate on failure.

<子>事情是这样的:

Something like this:

void * my_malloc(size_t size)
{
    void * const p = malloc(size);
    if (p || 0 == size) return p;
    terminate();
}

推荐答案

下面是glibc的声明:

Here is the glibc declaration:

extern void *memset (void *__s, int __c, size_t __n) __THROW __nonnull ((1));

__非空显示,该公司预计将指针非空。

The __nonnull shows that it expects the pointer to be non-null.

这篇关于可以memset的()与一个空指针称为如果大小为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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