你的 strcpy 函数对这些起作用的原因:
示例 1:
char t1[]="HelloWorld"; // you are defining arrays of characters in the data
char t2[]="TestString"; // segment. This are of memory has read/write access.
// You have effectively allocated and initiaized
// 22 bytes of data in read/write memory.
而这里(示例 2):
char* t1="HelloWorld"; // you are defining pointers in the data segment.
char* t2="TestString"; // these pointers point to data that is stored in
// the BSS segment, which is strictly read-only.
// You have allocated and initialized 16 bytes
// (2 pointers) in the data segment, and 22 bytes
// in read only memory.
当Strcpy() 试图覆盖BSS 段中受保护的数据时,会发生段错误。
有几种方法可以解决此问题。如示例 1 所示,您可以在全局数据空间中为目标字符串分配足够的内存,或者在堆栈上分配内存,或者再次在堆中分配一些内存。
#include <string.h>
#include <stdlib.h>
// read-only BSS segment.
const char* src = "HelloWorld"; // length: 10 + 1 null terminating character.
// global memory alllocation in DATA segment.
char global_mem_dest[11];
int main()
{
strcpy(global_mem_dest, src);
char stack_space_dest[11]; // on the stack.
strcpy(stack_space_dest, src);
char* heap_mem_dest_1 = (char*)malloc(strlen(src) + 1); // on the heap
if (heap_mem_dest_1)
{
strcpy(heap_mem_dest_1, src);
free(heap_mem_dest_1);
}
char* heap_mem_dest_2 = strdup(src); // on the heap, method 2.
if (heap_mem_dest_2)
free(heap_mem_dest_2);
// Note that method 2 allocates space and copies a string in one
// function call. This is probably what you are looking for.
char* heap_mem_dest_3 = new char[strlen(src) + 1]; // on the heap, the c++ way.
strcpy(heap_mem_dest_3, src);
delete[] heap_mem_dest_3;
return 0;
}
由于 strcpy() 返回一个指向你已经拥有的目标字符串的指针,它的返回值不是很有用,通常被忽略。