3

这段代码编译得很好,但在运行时会出现分段错误错误?谁能告诉我为什么?

#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;
}
4

8 回答 8

13

您为单个指针,分配了空间s1,但没有为 . 指向的字节分配空间s1

一种解决方案是动态分配内存s1

s1 = (char *)malloc(strlen(s2) + 1);
strcpy(s1, s2);

请记住,您需要malloc比 in 中的字符数多分配一个字节的内存(调用中的 +1),因为末尾s2有一个隐式字节。NULL

有关详细信息,请参阅C 内存管理(堆栈溢出)

于 2009-08-18T16:47:18.173 回答
4

您没有为 s1 分配内存。您有一个指向 s1 的指针,但没有为 strcpy 分配内存来将 s2 的值复制到其中。

char *s1 = malloc( strlen(s2) + 1 );

strcpy( s1, s2 );
于 2009-08-18T16:47:06.910 回答
3

您尚未为 s1 分配任何内存。它是什么都没有的指针。

char* s1 = malloc(sizeof(s2));
strcpy(s1, s2);
printf("%s", s1);
free(s1);
于 2009-08-18T16:47:48.033 回答
2

问题是 s1 没有与之关联的任何内存。strcpy不叫malloc()

你可以这样做:

char s1[10];

或者

char *s1 = malloc(10);

于 2009-08-18T16:47:38.313 回答
2

他们都说,你需要为s1分配空间。其他人发布的内容都可以正常工作,但是,如果您想要一种更简单的方法来为现有字符串分配空间并将其复制到新指针中,请像这样使用 strdup:

#include <stdio.h>
#include <string.h>
#include <math.h>

using namespace std;

int main() {
    const char s2[] = "asdfasdf";
    char* s1;

    s1 = strdup(s2);
    printf("%s", s1);

    return 0;
}

前面有人提到了strdup,那将是一种使用它的方法。大多数系统应该支持它,因为它在标准 C 库中。但显然有些人没有。因此,如果它返回错误,请使用已经提到的方法编写您自己的错误,或者只使用已经提到的方法;)

于 2009-08-18T16:59:49.803 回答
2

还没有人指出 strdup(字符串重复)解决这个问题的潜力。

#include <stdio.h>
#include <string.h>
#include <math.h>

using namespace std;

int main() {
    const char s2[] = "asdfasdf";
    char* s1;

    s1 = strdup(s2);  // Allocates memory, must be freed later.
    printf("%s", s1);

    free(s1);         // Allocated in strdup, 2 lines above
    return 0;
}
于 2009-08-18T17:05:09.170 回答
1

您需要分配目标(using namespace std;不是 C 而是 C++,其余代码是 C)。

于 2009-08-18T16:47:33.260 回答
0

您必须为指针 s1 分配内存。如果你不这样做,它将指向某个未知的地方,从而导致分段错误。正确的代码应该是:

#include <stdio.h>
#include <string.h>
#include <math.h>

int main() {
    const char s2[] = "asdfasdf";
    char* s1 = malloc(21 * sizeof(s2[0]));
    strcpy(s1,s2);
    printf("%s",s1);
    return 0;
}
于 2009-08-18T16:49:57.653 回答