简体   繁体   中英

Strcpy a static char array into a dynamically allocated char array to save memory

Say, in main(); you read a string from a file, and scan it into a statically declared char array. You then create a dynamically allocated char array with with length strlen(string).

Ex:

FILE *ifp;
char array_static[buffersize];
char *array;

fscanf(ifp, "%s", array_static);
array = malloc(sizeof(char) * strlen(array_static) + 1);
strcpy(array_static, array);

Is there anything we can do with the statically allocated array after copying it into the dynamically allocated array, or will it just be left to rot away in memory? If this is the case, should you even go through the trouble of creating an array with malloc?

This is just a hypothetical question, but what is the best solution here with memory optimization in mind?

Here's how to make your life easier:

/* Returns a word (delimited with whitespace) into a dynamically
 * allocated string, which is returned. Caller is responsible
 * for freeing the returned string when it is no longer needed.
 * On EOF or a read error, returns NULL.
 */
char* read_a_word(FILE* ifp) {
  char* word;
    /* Note the m. It's explained below. */
  if (fscanf(ifp, "%ms", &word) != 1)
    return NULL;
  return word;
}

The m qualifier in the scanf format means:

  • An optional 'm' character. This is used with string conversions ( %s , %c , %[ ), and relieves the caller of the need to allocate a corresponding buffer to hold the input: instead, scanf() allocates a buffer of sufficient size, and assigns the address of this buffer to the corresponding pointer argument, which should be a pointer to a char * variable (this variable does not need to be initialized before the call). The caller should subsequently free(3) this buffer when it is no longer required.

It's a Posix extension to the standard C library and is therefore required by any implementation which hopes to be Posix compatible, such as Linux, FreeBSD, or MacOS (but, unfortunately, not Windows). So as long as you're using one of those platforms, it's good.

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