简体   繁体   中英

Dynamic memory allocation of a string

how to dynamically allocate memory for a string?

I want to take a text file as input and want to store the characters of the file to a string.

First I count the number of character in the text file then dynamically allocate the string for this size and then want to the copy the text to the string.

main()
{


    int count = 0;  /* number of characters seen */
    FILE *in_file;    /* input file */

   /* character or EOF flag from input */
    int ch;

    in_file = fopen("TMCP.txt", "r");
    if (in_file == NULL) {
        printf("Cannot open %s\n", "FILE_NAME");
        exit(8);
    }

    while (1) 
    {
        ch = fgetc(in_file);
        if (ch == EOF)
            break;
        ++count;
    }
    printf("Number of characters is %d\n",
                  count);


    char *buffer=(char*)malloc(count*(sizeof(char)));
}

That's a terrible solution. You can determine the size of the file using a load of methods (search for tell file size, and especially for fstat ), and you can just mmap your file to memory directly, giving you exactly that buffer.

One option is to read the file a fixed-sized chunk at a time and extend the dynamic buffer as you read the file. Something like the following:

#define CHUNK_SIZE 512
...
char chunk[CHUNK_SIZE];
char *buffer = NULL;
size_t bufSize = 0;
...
while ( fgets( chunk, sizeof chunk, in_file ) )
{
  char *tmp = realloc( buffer, bufSize + sizeof chunk );
  if ( tmp )
  {
    buffer = tmp;
    buffer[bufSize] = 0; // need to make sure that there is a 0 terminator
                         // in the buffer for strcat to work properly.
    strcat( buffer, chunk );
    bufSize += sizeof chunk;
  }
  else
  {
    // could not extend the dynamic buffer; handle as necessary
  }
}

This snippet reads up to 511 characters from in_file at a time ( fgets will zero-terminate the target array). It will allocate and extend buffer for each chunk, then concatenate the input to buffer . In order for strcat to work properly, the destination buffer needs to be 0-terminated. This isn't guaranteed the first time around when the buffer is initially allocated, although it should be on sunsequent iterations.

Another strategy is to double the buffer size each time, which results in fewer realloc calls, but this is probably easier to grasp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM