I have an issue that is related to my programming project this semester. I have a dynamic array that has a structure, that structure contains a parameter for a string. The thing is I need to change that string from being static , to dynamic. I have written the function that asks for the string and stores it in a dynamic array and then returns it. Later in the program I will need to write the info from the arrays (in which the dynamic string is stored) to a binary file. How can I achieve this and how can I know when and how I am properly freeing the memory of that dynamic string? If I free the array in which the string is stored, do I also free the memory in which the string itself is stored?
My array which will store the string:
inspections *inspectionsArray;
char* dynamicString(){
char *stringPointer = NULL,*paux = NULL, char;
int stringSize = 1,stringEnd = 0,i;
stringPointer = (char*)malloc(sizeof(char));
if (stringPointer == NULL) {
printf("\nError alocating memory");
}else{
printf("\nEnter String: ");
while (char != EOF && char != '\n') {
char = getc(stdin); //Obter o char do stding
paux = realloc(stringPointer, stringSize*sizeof(char));
if (paux != NULL) {
stringPointer = paux;
stringPointer[stringEnd] = char; //meter o char na string
stringSize++; //incrementar o tamanho da string
stringEnd++;
}else{
printf("\nErro a realocar memoria para a string");
}
}
stringPointer[stringEnd] = '\0';
printf("\nString: %s", stringPointer);
}
return stringPointer;
}
The Structure in which I will have my string stored in.
typedef struct
{
//A bunch of parameters in here
char *dynamicString;
} inspection;
enter code here
Function I use to store data to array:
inspectionArray* registerInspection(inspection *inspectionArray){
char *string;
//I removed a bunch of code to not confuse things
string = dynamicString;
return inspection;
}
Function to save file:
void saveBinaryFile(inspection *inspections, int inspectionCounter)
{
FILE * inspectionArrayFile;
fileInspections = fopen("inspections.dat","wb");
if (fileInspections == NULL)
{
perror("\nError opening the file");
}
else
{
fwrite(&inspectionCounter, sizeof (int), 1, inspectionArrayFile);
fwrite(inspections, sizeof(tipoVeiculo), inspectionCounter, inspectionArrayFile);
// I write a bunch of stuff and verify it properly
fclose(inspectionArrayFile);
}
}
How do I properly read and free the string ?
I tried this:
void freeArrayStrings(inspections *inspectionsArray,int counter){
int i;
for (i=0; i<counter; i++) {
free(inspectionArray[i].dynamicString);
}
}