【问题标题】:strcat simulation in c [duplicate]c中的strcat模拟
【发布时间】:2013-05-31 15:42:31
【问题描述】:
#include<stdio.h>

main()
{
    char *str1="beautiful";
    char *str2="place";
    xstrcat(str1,str2);
}

xstrcat(char *s1,char *s2)
{

    char *temp;
    temp=s1;

    while(*s1!='\0')
    {
        s1++;
    }
    while(*s2!='\0')
    {
        s1++;
        *s1=*s2;
        s2++;
    }
    s1++;
    *s1='\0';
    printf("\n%s",temp);
}

错误输出: 程序收到信号 SIGSEGV,分段错误。 xstrcat 中的 0x000000000040055d (s1=0x400696 "place", s2=0x400696 "place") 在 strcat.c:23 23 *s1=*s2;

我无法在那个记忆中写作。谁能告诉我为什么会收到此错误。 ?

【问题讨论】:

  • 因为你不拥有那段内存。
  • 这个必须有很多重复...
  • @apprentice - 这些改进应该作为答案发布。修复 question 类型的失败 the purpose of SO ... ;-) 加上上下文丢失了,所以所有的响应/cmets 都不再有意义了。

标签: c arrays string


【解决方案1】:

str1 是一个字符串文字,写入该位置是未定义的行为。如果它是这样定义的,那么创建和写入str1 将是有效的:

char str1[100] = "beautiful";

【讨论】:

猜你喜欢
  • 2019-03-26
  • 1970-01-01
  • 2010-09-29
  • 2011-08-10
  • 2016-01-21
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多