How many chars can be in a char array?

后端 未结 6 769
广开言路
广开言路 2020-12-01 12:40
#define HUGE_NUMBER ???

char string[HUGE_NUMBER];
do_something_with_the_string(string);

I was wondering what would be the maximum number that I co

6条回答
  •  囚心锁ツ
    2020-12-01 12:59

    Declaring arbitrarily huge arrays to avoid buffer overflows is bad practice. If you really don't know in advance how large a buffer needs to be, use malloc or realloc to dynamically allocate and extend the buffer as necessary, possibly using a smaller, fixed-sized buffer as an intermediary.

    Example:

    #define PAGE_SIZE 1024  // 1K buffer; you can make this larger or smaller
    
    /**
     * Read up to the next newline character from the specified stream.
     * Dynamically allocate and extend a buffer as necessary to hold
     * the line contents.
     *
     * The final size of the generated buffer is written to bufferSize.
     * 
     * Returns NULL if the buffer cannot be allocated or if extending it
     * fails.
     */
     char *getNextLine(FILE *stream, size_t *bufferSize)
     {
       char input[PAGE_SIZE];  // allocate 
       int done = 0;
       char *targetBuffer = NULL;
       *bufferSize = 0;
    
       while (!done)
       {
         if(fgets(input, sizeof input, stream) != NULL)
         {
           char *tmp;
           char *newline = strchr(input, '\n');
           if (newline != NULL)
           {
             done = 1;
             *newline = 0;
           }
           tmp = realloc(targetBuffer, sizeof *tmp * (*bufferSize + strlen(input)));
           if (tmp)
           {
             targetBuffer = tmp;
             *bufferSize += strlen(input);
             strcat(targetBuffer, input);
           }
           else
           {
             free(targetBuffer);
             targetBuffer = NULL;
             *bufferSize = 0;
             fprintf(stderr, "Unable to allocate or extend input buffer\n");
    
           }
         }
       }
    

提交回复
热议问题