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

Of course you have "memory leak" because you never deallocate pointers to dynamically allocated country names placed in dynamically allocated countryList array of pointers. You deallocate the array of pointers only.

Of course you have "memory leak" because you never deallocate pointers to dynamically allocated country names placed in dynamically allocated countryList array of pointers. You deallocate the array of pointers only.

Yeah, but when I free just the array of pointers it says I have memory leak.

Nevermind, I was confused with what you were trying to say. When I try to do what you mentioned like this:

for (i=0;i<=numCountries;i++)
		free(countryList[i]);

There is a runtime error that tells me that I'm overwriting heap stacks or something.

Nevermind, I had a lot of arithmetic errors. I solved it now.

This article has been dead for over six months. Start a new discussion instead.