Nathan
Nathan

Reputation: 483

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.

Upvotes: 0

Views: 826

Answers (2)

Mikhail
Mikhail

Reputation: 8028

The variable is only guaranteed to live within the scope of the function. This includes the data you allocated for temp. Afterwords, anything can and will happen to those 1000 cells.

There is a second thing that is wrong with your function: It seems to be wrapping an existing function that already provides your target functionality.

Was

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

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

return ptr;
}// readFile

Works

char* readFile(FILE* fpFile, char* ptr, int n)
{
//  Statment
fgets(ptr, sizeof(char)*n, fpFile);
ptr = temp;
return ptr;
}// readFile
void fun()
{
//somehow File*
int num = 1000;
char* pointer = (char*) malloc(sizeof(char)*num);
pointer = readFile(file,pointer,num);
}

Should Be

void fun()
{
//somehow File*
int num = 1000;
char* pointer = (char*) malloc(sizeof(char)*num);
fgets(file,pointer*sizeof(char));
}

Upvotes: 0

Jeyaram
Jeyaram

Reputation: 9474

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

Upvotes: 4

Related Questions