new和malloc分配额外的16个字节 [英] new and malloc allocates extra 16 bytes

查看:275
本文介绍了new和malloc分配额外的16个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在VS2010 Windows 7中用c ++编写.我尝试读取大小为64字节的文件.这是代码:

I'm writing on c++ in VS2010 Windows 7. I try to read file of size 64 bytes. Here's the code:

    BYTE* MyReadFile(FILE *f)
{
    size_t result;
    BYTE *buffer;
    long lSize;
    if (f == NULL) 
    {
        fputs ("File error", stderr); 
        exit (1);
    }

    fseek (f, 0, SEEK_END);
    lSize = ftell (f);
    rewind (f);

    //buffer = (BYTE*) malloc (sizeof(char)*lSize);
    buffer = new BYTE[lSize];
    if (buffer == NULL) 
    {
        fputs ("Memory error", stderr); 
        exit (2);
    }

    result = fread (buffer, 1, lSize, f);
    if (result != lSize) 
    {
        fputs ("Reading error",stderr); 
        exit (3);
    }

    fclose (f);
    return buffer;
}

当我得到的文件大小是64时,但是当我用新的BYTE [lSize]为它分配内存时,我得到了80个字节的空间,因此产生了奇怪的序列ээээ««««««««оюою添加到缓冲区的末尾.你能告诉我如何处理吗?

When I get file size it is 64, but when I allocate memory for it with new BYTE[lSize] I get 80 bytes of space and thus strange sequence ээээ««««««««оюою is added to the end of buffer. Can you please tell me how to handle this?

推荐答案

已分配的字节数与看到的字节数之间存在重要区别.

There is an important difference between the number of bytes you have allocated, and the number of bytes that you see.

如果lsize为64,则说明您确实为自己分配了64个字节.这并不意味着在屏幕后面,C ++运行时将向Windows询问确切的64个字节.在实践中,内存管理器要求更多的内存,以便他们能够做自己的作业.通常,这些额外的字节是在从new/malloc返回的指针之前分配的,因此您永远不会看到它们.

If lsize is 64, you have indeed allocated yourself 64 bytes. This does not mean that behind the screen the C++ run time will have asked exactly 64 bytes to Windows. In practice memory managers ask slightly more memory so they are able to do their own homework. Often these extra bytes are allocated BEFORE the pointer you get back from new/malloc so you will never see them.

但是,这不是您的问题.问题是您使用fread从文件读取了64个字节. fread不可能知道您正在读取哪种数据.可能是一个结构,一个char缓冲区,一组双精度数,...它只是为您读取这些字节.

However, that is not your problem. The problem is that you read 64 bytes from file using fread. There is no way that fread knows what kind of data you are reading. It could be a struct, a char buffer, a set of doubles, ... It just reads these bytes for you.

这意味着,如果文件中包含字符"ABC",则您将获得准确的"ABC"字样.但是,在C语言中,字符串应以nul结尾,因此,如果将此缓冲区传递给printf,它将继续扫描内存,直到找到nul字符为止.

This means that if the file contains the characters "ABC" you will get exactly "ABC" back. BUT, in C, strings should be nul-terminated, so if you pass this buffer to printf, it will continue to scan memory until it finds a nul-character.

因此,要解决您的问题,请再分配1个字节,然后将最后一个字节设置为nul字符,如下所示:

So, to solve your problem, allocate 1 byte more, and set the last byte to the nul character, like this:

buffer = new BYTE[lSize+1]; 
buffer[lSize] = '\0';

这篇关于new和malloc分配额外的16个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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