Junk value from string using C

I'm not sure what's going on with my program, but I basically have a function that's trying to read a bunch of strings from a file and passes it back to main for further processing. Here's my code:

char* readFile(FILE* fpFile)
{
//  Local Declaration
char *ptr;
char temp[1000];

//  Statment
fgets(temp, sizeof(temp), fpFile);
ptr = temp;

return ptr;
}// readFile

The problem occurs once the function passes back the pointer to main. I tried printing the string, but I only get the first few lines correct and after it's junk. Also, if I were to print ptr in the function readFile it prints perfectly fine and the pointer that's being passed back to main prints fine also. Is there something that I am missing? Any help would be appreciated.

Here's the output I'm getting

2000 1990
New York-No. NJ; 21199865 19549649
Los Angeles area; 16373645 14531629
Chicago area; 9157540 8239820
Washington-Baltimore; 7608070 6727050
San Francisco area; 7039362 6253311
Philadelphia-Atlantic City area; 6188463 5892937
Boston\240\365\277_\377

There's supposed to be twice the amount of inputs, but it's stoping like a quarter of the way.

Answers


char temp[1000]; is local. when the control goes out of readFile(), that memory may be allocated to some other purpose. There are two ways, either storage may be a global array or dynamically allocated memory using malloc().

char* readFile(FILE* fpFile)
{
//  Local Declaration
char *ptr = malloc(1000);

//  Statment
fgets(ptr, 1000, fpFile);

return ptr;
}// readFile

Need Your Help

iOS compiling gives codesigning error

iphone xcode ios build

I am trying to build my application and I get the following:

Continuous Integration Fix for NAnt 0.86 Beta 1 with .NET 3.5

.net .net-3.5 .net-2.0 cruisecontrol.net nant

I have been trying to use the latest NAnt (0.86 Beta 1) for a few weeks now in