【问题标题】:find bugs in the c++ code below [closed]在下面的 C++ 代码中查找错误 [关闭]
【发布时间】:2014-11-04 06:02:23
【问题描述】:

我被要求在以下代码中查找错误 这段代码只是打印 abcdef,对我来说似乎没什么害处,但会感谢任何建议

#include <iostream>
using namespace std;

const char* append(const char* s1, const char* s2) {    
    string s(s1);    
    s += s2; 
    return s.c_str();
} 
void foo() { 
    const char* total = append("abc", "def"); 
    cout<<"total = "<<total<<endl;
}

int main() { 
  foo();
  return 0;
}

【问题讨论】:

  • 提示:当append 返回时,s 将不复存在。
  • 当 s 超出范围时,它将删除指针,因此从 append 函数返回的将包含垃圾字符。
  • 谢谢大家,这解决了我的困惑
  • 代码缺少#include &lt;string&gt;所以不会编译......

标签: c++


【解决方案1】:

你有一个悬空指针。 s 在超出范围时被销毁,这意味着指向其内部数据的指针不再有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-23
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多