Create array of characters on heap instead of stack

Asked By: Anonymous

I need a character array to store the data of a file, and the file can have up to 30,000 characters in it. I tried doing this:

char buf[30000]

But, this seemed like an easy way to accidentally cause a stack overflow or some other error. So, I tried using calloc like this:

char* buf = calloc(30000, 1);

But Visual Studio told me something about dereferencing, so how would I do this?

Code:

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

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

    FILE* fp;

    printf("Enter name of a file you wish to seen");
    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;
}

Solution

Answered By: Anonymous

ALWAYS check the result of a malloc, calloc, or realloc call – they will return NULL if they cannot satisfy the request. Based on your comment, the calloc call failed, so trying to access buf[i] is raising an error.

Add a check as follows:

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++;
}
techinplanet staff

techinplanet staff


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno