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?
array_staticgoes out of scope it disappears so it doesn't "rot away". Do you know about "stack" and "heap" memory ?nulcharacter (add 1 to the return value of thestrlencall). Also, look at thestrdupfunction.array_staticis inmainthen it never goes out of scope. If it was in a function etc then it would.sizeof(char) * strlen(array_static) + 1is conceptually wrong, should besizeof(char) * (strlen(array_static) + 1). Yet sincesizeof(char) == 1, it has the same result.