c++ - 将空指针传递给 fwrite 会导致问题

标签 c++ fwrite

我最近编写了一些代码,在某些情况下,空指针可能会传递给 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)将未定义的行为转换为已定义的行为

关于c++ - 将空指针传递给 fwrite 会导致问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46662837/

相关文章:

c++ - QML - 不支持命令式代码

php - CSV 根据内容调整列大小

c - fwrite 创建一个比输入文件大的输出文件

c++ - 点集上的 2d 旋转会导致倾斜失真

c - 读写不同的值

c++ - 使用 fgetc/fwrite 的简单字节更改失败

php - fwrite() 返回什么类型?

c++ - 为什么我的 C++ 代码中会出现断点?

C++ 日期和时间

c++ - 减少大数据的条件语句