对于 char * varable,如何在调试模式下查看其值

For char * varable, how to view its value in debug mode

本文关键字:模式 调试 char varable 对于      更新时间:2023-10-16

我在下面编写了代码,通过VC2017回读二进制文件。在调试模式下,我喜欢看到"缓冲区"中的值。但我看不到可读的值。我的问题是:

  1. 如何查看可读结果?
  2. 做了"sizeof(buffer)",它返回了 4,这比我预期的要少。我希望缓冲区的大小和文件大小相同。为什么?

非常感谢你启发我。

char* read_back(const char* filename) 
{
    FILE* pFile;
    long lSize;
    char* buffer;
    pFile = fopen(filename, "rb");
    if (pFile == NULL)
    {
        fputs("File error", stderr);
        exit(1);
    }
    fseek(pFile, 0, SEEK_END);
    lSize = ftell(pFile);
    rewind(pFile); // set file pos at the begining
    // copy the file into the buffer:
    buffer = (char*)malloc(sizeof(char)*lSize);
    size_t result = fread(buffer, 1, lSize, pFile);
    if (result != lSize)
    {
        fputs("Reading error", stderr);
        exit(3);
    }
    fclose(pFile);
    return buffer;
}

下面介绍如何用C++编写代码(不是你实际拥有的 C 代码)

#include <fstream>
#include <sstream>
#include <string>
std::string read_back(const char* filename)
{
    std::ifstream file(filename, std::ios_base::binary);
    std::ostringstream buffer;
    buffer << file.rdbuf();
    return buffer.str();
}

它返回一个 std::string 而不是一个 char*,但这是一件好事,因为您没有记住必须释放分配的内存的问题。

如前所述,您误解了指针和大小的工作方式。避免指针,它们很难。