在堆上而不是堆栈上创建字符数组

Create array of characters on heap instead of stack

我需要一个字符数组来存储文件的数据,文件最多可以有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;
}

ALWAYS 检查 malloccallocrealloc 调用的结果- 如果不能满足请求,他们将 return 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++;
}