开发者

Passing a local buffer to function

开发者 https://www.devze.com 2023-03-20 16:33 出处:网络
I am passing a local buffer to a function: void func1() { char buffer[128]; func2(buffer); } void func2(char *buff)

I am passing a local buffer to a function:

void func1()
{
    char buffer[128];
    func2(buffer); 
}

void func2(char *buff)
{
     strcpy(buff, "Some String");
}

Now when I look at the value of buff after function call, it just has "S" and rest is empty.开发者_如何学JAVA

Now, if I make buffer global or static, then I can rx the whole string.

My question here is that we are passing the address of buffer to the function, so it should not matter if it is local or global. But, for the case of declaring as local, I do not get data back in my buffer.


Because you declared your buffer on the stack, it is undefined after func1 exits. If you declared it to be global or static, however, its scope would not be restricted to the function call and thus you could continue to access it. Just having the buffer's address does not magically make its contents valid.


When you say "the value of *buff" in the debugger, you realize that is just one character of the string, right? The rest of the characters are next to it on the stack.

I'm not going to bother running this code. Everyone else here says it is working just fine.


Your code is ok - how are you looking at the contents of the buffer? If you add a printf("%s\n", buffer) at the end of func1(), you'll see that it's working just fine.


It is not obvious what is wrong here, but since you have tagged the question "RTOS", is it possible that this task's stack is too small to accommodate a 128 byte array?

0

精彩评论

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

关注公众号