cpp函数返回垃圾字符串值

我正在测试CPP中关于字符串数据类型的东西。我正在运行以下代码:

    #include <iostream>
    #include <string.h>
    #include <stdio.h>
    using namespace std;
    char* myname() {
        char str[5] ;
        str[0] = 'a';
        str[1] = 'b';
        str[2] = 'c';
        str[3] = '\0';
        //printf("BEFORE[%s]__",str);
        string aa = str;
        string aa2 = "";
        aa2+=aa[0];
        aa2+=aa[1];
        aa2+=aa[2];
        aa2+=aa[3];
        return &aa2[0];
    }


    int main() {
        printf("AFTER[%s]\n",myname());
        return 0;
    }

编译器版本:

    user@822e36b19146:~/data$ g++ --version
    g++ (Ubuntu 5.4.0-6ubuntu1~16.04.6) 5.4.0 20160609
    Copyright (C) 2015 Free Software Foundation,Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or fitness FOR A PARTICULAR PURPOSE.

我正在我的机器上获取垃圾值:

    user@822e36b19146:~/data$ g++ -o test test.cpp
    user@822e36b19146:~/data$ ./test
    AFTER[��p��]
    user@822e36b19146:~/data$ ./test
    AFTER[�7���]

我尝试在在线编译器上运行相同的代码。有些有效,有些无效。

  1. 不工作:http://coliru.stacked-crooked.com/a/ce4bc39767b29e44
  2. 不工作:https://wandbox.org/permlink/C8ATffE4wysy3il0
  3. 工作:https://ideone.com/NV0mUM
  4. 工作:http://cpp.sh/8cctv

一个奇怪的行为是我观察到在返回之前打印任何东西。使代码正常工作。在我尝试的取消注释行//printf("BEFORE...中 得到以下输出:

    user@822e36b19146:~/data$ g++ -o test test.cpp
    user@822e36b19146:~/data$ ./test
    BEFORE[abc]__AFTER[abc]
    user@822e36b19146:~/data$ ./test
    BEFORE[abc]__AFTER[abc]

请任何人帮助我理解这一点。

klmMMM 回答:cpp函数返回垃圾字符串值

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3159322.html

大家都在问