char **makeString ( const int numOfArrays, const int sizeOfEachArray ) {
/* Function to create an array of strings: ( Array of pointers to strings ) */
/* Local variables */
int i, j;
//int numOfArrays = 6;
/*char stringsToCopy[6][12] = {"Hello", "Good-Bye!", "Greetings",
"Pointers", "Arrays", "Programming"}; */
char **stringArray = NULL;
if ( ( (numOfArrays) && (sizeOfEachArray) ) == (int)NULL ) {
/* Free memory */
for (j = 0; j < numOfArrays; j++) {
free(stringArray[j]);
}
free(stringArray);
}
/* Allocate room for numOfArrays */
stringArray = malloc(numOfArrays * sizeof *stringArray);
/* If allocation succeeded */
if (stringArray != NULL) {
/* Loop through all columns */
for (i = 0; i < numOfArrays; i++) {
/* Allocate */
stringArray[i] = malloc( (sizeOfEachArray) + 1);
}
}else {
/* Allocation failed */
return NULL;
}
/* End program */
return stringArray;
}
int main(void)
{
int i;
int j;
char **stringArray2 = NULL;
//char *point;
/*while ( ( point = getDirectoryFiles () ) != NULL ) {
printf ( "in main \"%s\"\n", point);
}*/
stringArray2 = makeString ( 5, 50 );
strcpy ( stringArray2 [0], "This is a string 0" );
strcpy ( stringArray2 [1], "This is a string 1" );
strcpy ( stringArray2 [2], "This is a string 2" );
strcpy ( stringArray2 [3], "This is a string 3" );
strcpy ( stringArray2 [4], "This is a string 4" );
/* Print data */
for (i = 0; i < 5; i++) {
printf("%s\n", stringArray2[i]);
}
makeString ( (int)NULL, (int)NULL );
return(0);
}
I have this code it works but I want to know if I am having a memory leak...
I can't free stringArray2 from main and if I free it in the makeString function I can't return it (it would have been freed)... Do I have a memory leak?, How can I prevent this? Thanks in advance... (the problem is I can't find a way to free stringArray in makeString and return the information it has...)