【问题标题】:Create array of characters on heap instead of stack在堆而不是堆栈上创建字符数组
【发布时间】:2021-08-09 03:09:15
【问题描述】:

我需要一个字符数组来存储文件的数据,该文件最多可以包含 30,000 个字符。我试过这样做:

char buf[30000]

但是,这似乎是一种意外导致堆栈溢出或其他错误的简单方法。所以,我尝试像这样使用 calloc:

char* buf = calloc(30000, 1);

但是 Visual Studio 告诉我一些关于取消引用的事情,那么我该怎么做呢?

代码:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char  ch;
    char filename[256] = "";

    FILE* fp;

    printf("Enter name of a file you wish to see\n");
    gets(filename);

    fopen_s(&fp, filename, "r"); // read mode

    if (fp == NULL) {
        perror("Error while opening the file.\n");
        exit(EXIT_FAILURE);
    }

    int i = 0;
    char* buf = calloc(30000, 1);

    while ((ch = fgetc(fp)) != EOF) {
        buf[i];
        i++;
    }
    fclose(fp);
    return 0;
}

【问题讨论】:

  • 您需要明确说明什么是“取消引用”。
  • 您需要给我们一个minimal reproducible example 以便我们查看问题所在。
  • @Finxx 表示您正在将程序编译为 C++ 程序。写 char* buf = ( char * )calloc(30000, 1);
  • buf[i]; 应该是buf[i] = ch;
  • char ch; 应该是int ch;

标签: arrays c visual-studio heap-memory


【解决方案1】:

总是检查 malloccallocrealloc 调用的结果 - 如果它们不能满足请求,它们将返回 NULL。根据您的评论,calloc 调用失败,因此尝试访问 buf[i] 会引发错误。

添加如下检查:

char* buf = calloc(30000, 1);
if ( !buf )
{
  /**
   * calloc could not satisfy the request - bail out at this point.
   */
  fprintf( stderr, "memory allocation failed!\n" );
  fclose( fp );
  exit( EXIT_FAILURE );
}

/**
 * You also need a check here to make sure you don't
 * read more characters than your array is sized to 
 * hold.  That should be easy enough to figure out. 
 */
while ((ch = fgetc(fp)) != EOF) {
    buf[i] = ch;
    i++;
}

【讨论】:

  • 尚不清楚 OP 的 calloc() 调用 did 是否失败,vs。基于静态分析的 Visual Studio 警告它可能失败,在这种情况下程序将显示 UB。
猜你喜欢
  • 1970-01-01
  • 2014-05-13
  • 2016-10-15
  • 2010-12-08
  • 2010-10-15
  • 1970-01-01
  • 2017-03-15
  • 2010-10-03
相关资源
最近更新 更多