将 Nullpointer 传递给 fwrite 会导致问题

Can passing a Nullpointer to fwrite cause problems

我最近写了一些代码,在某些情况下,空指针可能会传递给 fwrite

虽然它在 windows 上有效,但我想知道它是否会在其他平台上引起问题,或者是否有任何东西可以阻止它。


我怎么弄得这么乱 ;) :

std::vector<unsigned char> bytes;

// ...
// bytes could be filled but may be empty.

const char* bytesToWrite = (const char*) bytes.data();   // .data() will return NULL if empty
unsigned long count = bytes.size();

if (count == fwrite(bytesToWrite, 1, count, handle)) //...

来自微软 documentation:

fwrite returns the number of full items actually written, which may be less than count if an error occurs. Also, if an error occurs, the file-position indicator cannot be determined. If either stream or buffer is a null pointer, or if an odd number of bytes to be written is specified in Unicode mode, the function invokes the invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, this function sets errno to EINVAL and returns 0.

所以它在 Windows 中有效(好吧,你得到一个明确的错误而不是大声的崩溃,但它仍然不是很有用)。但是 Unix/Linux 中没有这种情况的踪迹,所以不要依赖它。总是事先测试:

if (buffer != NULL) { fwrite(buffer, ...

或使用assert(buffer != NULL)将未定义的行为变成定义的行为

如果您添加额外的 if 来检查 NULL ptr,只会对性能造成很小的影响。

NULL 传递给 fwrite 是未定义的行为,在最好的情况下可能会导致分段错误。

将您的代码更改为:

const char* bytesToWrite = (const char*) bytes.data();   
if(bytesToWrite != NULL)
{
    unsigned long count = bytes.size();

    if (count == fwrite(bytesToWrite, 1, count, handle)) //...
}