C 中的简单字符串运行时错误?
这段代码编译得很好,但运行时出现分段错误错误? 谁能告诉我为什么吗?
#include <stdio.h>
#include <string.h>
#include <math.h>
int main() {
const char s2[] = "asdfasdf";
char* s1;
strcpy(s1, s2);
printf("%s", s1);
return 0;
}
This code compiles fine but give segmentation fault error while running? Can anyone tell why?
#include <stdio.h>
#include <string.h>
#include <math.h>
int main() {
const char s2[] = "asdfasdf";
char* s1;
strcpy(s1, s2);
printf("%s", s1);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您没有为 s1 分配内存。 您有一个指向 s1 的指针,但没有为 strcpy 分配内存来将 s2 的值复制到其中。
You didn't allocate memory for s1. You have a pointer to s1 but no memory allocated for the strcpy to copy the value of s2 into.
您尚未为 s1 分配任何内存。 它是一个空无一物的指针。
You have not allocated any memory to s1. It is a pointer to nothing.
问题是 s1 没有任何与之关联的内存。
strcpy
不会调用malloc()
。您可以这样做:
char s1[10];
或
char *s1 = malloc(10);
The problem is that s1 does not have any memory associated with it.
strcpy
does not callmalloc()
.You could either do:
char s1[10];
or
char *s1 = malloc(10);
您为单个指针
s1
分配了空间,但没有为s1
指向的字节分配空间。解决方案是为
s1
动态分配内存:请记住,您需要比数字多分配一个字节的内存(调用
malloc
时的 +1)s2
中的字符数,因为末尾有一个隐式的NULL
字节。有关详细信息,请参阅 C 内存管理(堆栈溢出)。
You allocated space for a single pointer,
s1
, but not the bytes pointed at bys1
.A solution is to dynamically allocate memory for
s1
:Keep in mind that you need to allocate one more byte of memory (the +1 in the call to
malloc
) than the number of characters ins2
because there is an implicitNULL
byte at the end.See C Memory Management (Stack Overflow) for more information.
他们都说,你需要为 s1 分配空间。 其他人发布的内容都可以正常工作,但是,如果您想要一种更简单的方法来为现有字符串分配空间并将其复制到新指针中,请像这样使用 strdup :
有人之前提到过 strdup,这将是一种使用方法它。 大多数系统应该支持它,因为它位于标准 C 库中。 但显然有些人不这么认为。 因此,如果它返回错误,请使用已经提到的方法编写自己的错误,或者仅使用已经提到的方法;)
What they all said, you need to allocate the space for s1. What everyone else has posted will work just fine, however, if you want a simpler way to allocate space for an existing string and copy it into a new pointer then use strdup like this:
Someone mentioned strdup earlier, that would be a way to use it. Most systems should support it since it is in the standard C libaries. But apparently some don't. So if it returns an error either write your own using the method already mentioned, or just use the method already mentioned ;)
目前还没有人指出 strdup(字符串重复)解决这一问题的潜力。
No one yet has pointed out the potential of strdup (String Duplicate) to address this problem.
您需要分配目标(并且
using namespace std;
不是 C,而是 C++,其余代码是 C)。You need to allocate the destination (and
using namespace std;
isn't C but C++, the rest of the code is C).您必须为指针 s1 分配内存。 如果你不这样做,它将指向未知的地方,从而出现分段错误。 正确的代码应该是:
You have to allocate memory to the pointer s1. If you don't do that, it will be pointing somewhere unknown, and thus arriving at the segmentation fault. The correct code should be: