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:
The
mqualifier in the scanf format means: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.