【问题标题】:Copy one string into another将一个字符串复制到另一个
【发布时间】:2021-08-28 05:59:33
【问题描述】:

当下面的代码运行时,它给出了某种段错误并且程序崩溃了。 所以最初 temp = "abcdef" 最后 temp3 也应该包含 "abcdef"

My intention is to copy the content of "temp" into
 "temp3".Please suggest where I am doing wrong.

void fun (char * input , char **input1) {

size_t size = strlen(input);
*input1 = (char **) malloc(sizeof(char) * (size+1));
memcpy(*input1 , input , size);
}

int main(){

char * temp = "abcdef";
char * temp3;

fun(temp , temp3);
printf("%s",temp3);

return 0;
}

【问题讨论】:

  • 打开你的编译器警告......并注意它们!您还需要为终止'\0'分配strlen + 1
  • 这不会编译。至于问题,同样是老无聊的“off by 1没有为空终止符分配空间”的常见问题解答,之前已经回答过无数次了。我懒得找副本了。
  • 关闭选民:这不仅仅是一个错字。
  • @ashwinak 设置 -> 编译器 -> 编译器标志选项卡。检查以下内容:“启用所有常见的编译器警告(覆盖许多其他设置)-Wall”、“启用额外的编译器警告 -Wextra”、“将严格的 ISO C 和 ISO C++ -pedantic-errors 要求的警告视为错误”。您可能需要为 -Werror 添加一个自定义项。
  • 至于“它只给了我一个警告”请查看What must a C compiler do when it finds an error?

标签: c copy dynamic-memory-allocation c-strings function-definition


【解决方案1】:

对于初学者来说,函数的第二个参数

void fun (char * input , char **input1) {

在您传递char * 类型的表达式时,具有char ** 类型。

char * temp3;

fun(temp , temp3);

所以程序已经有未定义的行为。你需要像这样调用函数

fun(temp , &temp3);

在函数中你必须至少编写以下内容

size_t size = strlen(input) + 1;
*input1 = malloc(sizeof(char) * size);
memcpy( *input1 , input , size);

即你需要计算源字符串的终止零字符'\0'

并且函数的第一个参数应该有限定符const

void fun ( const char * input , char **input1);

在程序结束时,你应该释放函数中分配的内存

free( temp3 );

检查内存是否分配成功会更安全。例如

void fun( const char * input , char **input1 )
{
    size_t size = strlen(input) + 1;
    *input1 = malloc(sizeof(char) * size);

    if ( *input1 ) memcpy( *input1 , input , size);
}

主要你可以写

fun(temp , &temp3);
if ( temp3 ) puts( temp3 );

free( temp3 );

【讨论】:

    猜你喜欢
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多