简体   繁体   English

在C ++中传递C-Strings的问题

[英]Issue passing C-Strings in C++

I'm not C++ developer and I'm trying to figure out why when I return a C-string from a function I'm getting garbage out. 我不是C ++开发人员,我想弄清楚为什么当我从一个函数返回一个C字符串时,我会得到垃圾。

#include <stdio.h>

const char* tinker(const char* foo);

int main(void)
{
    const char* foo = "foo";
    foo= tinker(foo);
    printf(foo); // Prints garbage
    return 0;
}

const char* tinker(const char* foo)
{
    std::string bar(foo);
    printf(bar.c_str());  // Prints correctly
    return bar.c_str();
}

You're returning a C-string that's based on the internal memory of a std::string . 您将返回一个基于std::string内部内存的C std::string However, this is being printed AFTER your bar is destructed. 但是,这是在您的bar被破坏后打印的。 This memory is garbage by the time it reaches the printf(foo); 到达printf(foo);时,这个内存是垃圾printf(foo); line. 线。

You're returning a pointer to a buffer internal to bar , but then you're destroying bar (and the buffer) before you use that pointer. 你正在返回一个指向bar内部缓冲区的指针,但是在你使用该指针之前你正在销毁bar (和缓冲区)。

If you need the content of bar after the function returns, return bar instead of bar.c_str() . 如果在函数返回后需要bar的内容,则返回bar而不是bar.c_str()

To add to what others said, this is one way to get it to work: 要添加其他人所说的,这是让它工作的一种方法:

#include <stdio.h>

std::string tinker(const char* foo);
int main(void)
{
     const char* foo = "foo";
     std::string foo2= tinker(foo);
     printf(foo2.c_str()); // Prints correctly
     return 0;
}  

std::string tinker(const char* foo)
{     
     std::string bar(foo);
     return bar; 
} 

Here the std::string object is copied* through the return value and you are printing the copy in main(). 这里std :: string对象通过返回值复制*,然后在main()中打印副本。

*popular string implementations employ optimizations like reference counting that avoid actually copying the string. *流行的字符串实现采用像引用计数这样的优化来避免实际复制字符串。 In addition, in C++0x the string object will be moved, not copied. 此外,在C ++ 0x中,字符串对象将被移动,而不是被复制。

Because you're allocating bar in tinker's stack. 因为你在修补堆栈中分配了条形码。 When tinker ends, its stack is reclaimed, bar is deleted, so the pointer you're returning points to deallocated memory, ie it's not valid anymore when you exit the function. 当修补程序结束时,其堆栈被回收,bar被删除,因此您返回的指针指向已释放的内存,即退出该函数时它不再有效。

return bar.c_str();

该行返回临时对象的char* ,该函数在函数末尾被删除,因此main() foo指向已删除的对象char*

Because bar lives on tinker's stack; 因为酒吧生活在修补堆上; after leaving the function, its c_str() is gone. 离开函数后,它的c_str()消失了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM