For some reason I'm getting a memory leak error. It's probably from the part where I start to copy the strings and allocate an array of characters, but I have no idea why. I'm using a text file for input data, which is found here: http://puma.deanza.edu/distribute/DeliaG/Fall_2008/CIS15BG/BG_Labs/BG_Lab_6/countries.txt
I appreciate anyone who helps me solve this issue :]
#include <stdio.h>
#include <stdlib.h>
#include <crtdbg.h>
#define FILE_IN "countries.txt" // user is free to change filename
// Prototype Declarations
char **getNames ( void );
int main (void)
{
// Local Definitions
char **countryList;
int i;
// Statements
printf("\t\t LAB 6 - Strings\n\n" );
countryList = getNames();
free(countryList);
printf( _CrtDumpMemoryLeaks() ? "Memory Leak\n" : "No Leak\n");
printf("\n\t\tEnd of Lab 6\n"
"\n\t\tHave a great day!\n");
return 0;
} // main
char **getNames ( void )
{
// Local Declarations
FILE *spIn;
int numCountries = 0;
char tempAry[50];
char **countryList;
int i;
int closeResult;
// Statements
if ( ! ( spIn = fopen ( FILE_IN , "r" ) ) )
{
printf("Error loading input file.\n");
exit(100);
}
while(fgets(tempAry, sizeof(tempAry), spIn))
numCountries++;
printf("Number of countries: %d\n", numCountries);
closeResult = fclose ( spIn );
if (closeResult==EOF)
{
printf("File did not close properly.\n");
exit(101);
}
if ( ! ( spIn = fopen ( FILE_IN , "r" ) ) )
{
printf("Error loading input file.\n");
exit(102);
}
if ( ! ( countryList = (char**) calloc (numCountries + 1, sizeof(char*))))
{
printf("Memory is unavailable.\n");
exit(103);
}
for ( i = 0; i < numCountries; i++ )
{
fgets(tempAry, sizeof(tempAry), spIn);
countryList[i] = (char*) calloc (strlen(tempAry), sizeof(char));
strcpy(countryList[i], tempAry);
printf("%s", countryList[i]);
}
countryList[numCountries] = '\0';
closeResult = fclose ( spIn );
if (closeResult==EOF)
{
printf("File did not close properly.\n");
exit(104);
}
return countryList;
} // getNames