c+中的分段错误+;程序 下面有一个C++代码。

c+中的分段错误+;程序 下面有一个C++代码。,c++,runtime-error,C++,Runtime Error,#include<iostream> #include <cstring> using namespace std; void f(const char* s) { char* temp; strcpy(temp,s); cout<<temp<<endl; } int main() { f("HELLO"); return 0; } 它编译时没有任何错误。但是当我用/output 它给出了一个错误分段错误

#include<iostream>
#include <cstring>
using namespace std;
void f(const char* s)
{
    char* temp;
    strcpy(temp,s);

    cout<<temp<<endl;
}
int main()
{
    f("HELLO");
    return 0;
}
它编译时没有任何错误。但是当我用
/output

它给出了一个错误分段错误(堆芯转储)
有什么问题吗??
附言:

操作系统是Ubuntu 14.04 LTS

您没有为
temp
分配任何空间。它被定义为指向字符类型的指针,并将初始化为某个随机值。当您
strcpy
将字符串复制到该字符指针指向的内存中时,它将尝试将字符串“HELLO”中的字节复制到该内存中,这几乎肯定是无效的


要更正此问题,请确保
temp
已分配一些实际存储。
chartemp[buffer\u size]
或使用
malloc
new
。或者,因为这是C++而不是C,所以使用C++代码库中的类型。 所以temp是一个未初始化的指针。结果是未定义的行为

你把这个标记为C++,所以你可以考虑:

void f(const char* s)
{
   std::string temp(s);
   std::cout<<temp<<std::endl;
}
void f(常量字符*s)
{
标准:字符串温度;

std::coutonilized局部变量,如
temp
变量,具有不确定(实际上是随机的)值。使用它们会导致崩溃,这是一个非常常见的原因。这里的要点是,您需要以某种方式为指针分配内存。您从不为
temp
char*temp;
分配内存。此外,还有任何不使用
std::string
而不是
char*
void f(const char* s)
{
   std::string temp(s);
   std::cout<<temp<<std::endl;
}