c++ - 预期 malloc 函数的大小不同

标签 c++ size malloc

解决方案可能微不足道,但我对 cpp 并不了解。

在我执行代码后,function strlen((char*)buffer) 的值比我想象的要高。这是为什么?我该如何解决? (如果 filesize=48,则 strlen((char*)buffer)=64 并且它也应该是 48!)

    ifstream iffile;
    iffile.open(argv[1], ios::in | ios::binary | ios::ate);
    if (iffile.is_open())
    {
       long filesize = iffile.tellg();
       if (filesize > 0)
       {
           iffile.seekg(0, ios::beg);
           {
                 long pos = iffile.tellg();
                 if (pos != filesize)
                 {
                       char *buffer;
                       buffer = (char *)malloc(filesize * sizeof * buffer);
                       if (buffer != NULL)
                       {
                             memset(buffer, 0, filesize - pos);
                             iffile.read((char *)buffer, filesize);

此外,我不得不提一下,在我的文件中有很多不可打印的值。

最佳答案

您的代码假定该文件包含一个终止字符 '\0',以将字符数组变成一个字符串。此终止符是 strlen() 查找的内容,因此如果它不存在,您必须添加它。

一种确定的方法是 malloc()(顺便说一下,它应该是 new[] 或 C++ 中更高级的东西)比 file_size,加载后设置为'\0'

此外,您必须检查分配和 I/O 是否成功。

关于c++ - 预期 malloc 函数的大小不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15390243/

相关文章:

c++ - C++ 编程中的 vector 类

c++ - 如何使用 Qt5 编写 C++11?

objective-c - 使用 UIImageJPEGRepresentaion() 将 UIImage 转换为 NSData 并将其保存到文件会增加文件大小(以字节为单位)

java - 根据屏幕分辨率以编程方式创建 View

C++ malloc 错误

c - 微 Controller 在 malloc 失败

具有私有(private)构造函数的 C++ 静态列表

java - JMF - 大文件 (2GB) - 无 'movi' block 错误

c++ - 为什么 Valgrind 在未释放 malloc 内存后不报告任何问题?

c++ - 为什么不可能重载 CUDA C++ 类的主机/设备成员函数