I’m a little stuck here… When using this conReadLine() function twice, it returns the same address as the second string I read in earlier. For example, if it asks for a name twice, and I enter “NameA” and “NameB”, the stored results are “NameB” and “NameB”. I understand why this is happening, but I can’t figure out how to solve it. Declaring ‘buffer’ as static is going to do the same thing. How can I get this function to return a separate address on each string?
const char *conReadLine(void)
{
char buffer[MAX_BUFFER];
fgets(buffer, MAX_BUFFER, stdin);
// Check for newline character.
char *newline = strchr(buffer, '\n');
if (newline)
*newline = '\0';
return buffer;
}
Doing this:
Is returning a pointer to deallocated stack which is very bad. it also brings unpredictable results which includes reusing the same address with other invocations and even other function all together!
you need to do this instead:
which will get you a fresh memory location every time. just remember to
freeit when you are done with it.