开发者

How to return a ReadLine() function in C?

开发者 https://www.devze.com 2023-03-29 16:21 出处:网络
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 \"Na

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 happe开发者_如何转开发ning, 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:

const char *conReadLine(void)
{   
    char buffer[MAX_BUFFER];
    // something
    return buffer;
}

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:

const char *conReadLine(void)
{   
    char *buffer = (char*)malloc(MAX_BUFFER);
    // something
    return buffer;
}

which will get you a fresh memory location every time. just remember to free it when you are done with it.


It is a classic!

The function returns a pointer to an inner variable (the buffer). So, basically, your data is in part of the memory (the stack) where successive call to other functions will overwrite it.

In this case, as you call the same function twice, the position of the variables is exactly the same. So, the memory where nameA is written, is overwritten with nameB and the following call.

more fun: create a function

const char *intermediate(void) {
  char buffer[MAX_BUFFER];
  return conReadLine();
}

the first time call conReadLine and the second one intermediate. The extra function call and the local variable will have "desplaced" the memory location so it will no longer overwrite it!

Two solutions:

1) instead of storing the data in a static defined buffer, get some memory from the heap using malloc (remember to freeit when it no longer is necessary).

2) after the first call, copy the contents of the buffer in another location so you can have them disponible when you need it.

Welcome to the world of C pointers!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号