【问题标题】:how to return a char* array from a function of strcpy and store it in another char* array?如何从 strcpy 函数返回一个 char* 数组并将其存储在另一个 char* 数组中?
【发布时间】:2021-06-14 04:32:01
【问题描述】:

我创建了一个 strcpy 函数来将一个字符串复制到另一个字符串。当两个 char[] 数组通过它时它工作得非常好,但是当 char* 数组通过它时它会给出分段错误(核心转储)错误。如何解决?

#include <iostream>

using namespace std ;

char* Strcpy ( char* s1 , const char* s2 )
{
while(*s2 != '\0')
{
*(s1)=*(s2);
s1++;
s2++;
}
*s1='\0';

return s1;
}

int main()
{

/*char t1[]="HelloWorld";  //it is working fine for both these arrays
char t2[]="TestString";*/

char* t1="HelloWorld";    //Segmentation fault
char* t2="TestString";

char* r=Strcpy(t1,t2);

cout<<r<<endl;

cout << t1;
}

【问题讨论】:

  • 您正在尝试复制到常量文字字符串空间。该内存区域受到保护,不会被写入。
  • 该代码应该会产生一些警告。你应该认真对待这些。

标签: c++ arrays char heap-memory


【解决方案1】:

你的 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() 返回一个指向你已经拥有的目标字符串的指针,它的返回值不是很有用,通常被忽略。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    相关资源
    最近更新 更多