2

While doing some programs on strings, I have come across this little problem. The question which was asked to me was this - Write a pointer version of the function strcat(s,t) which copies the string t to the end of s. I wrote the program as this -

#include<stdio.h>
void strcat(char *s, char *t);
int main()
{
    char *s1, *s2;
    printf("enter the first string\n");
    scanf("%s",s1);
    printf("Enter the second string\n");
    scanf("%s",s2);
    strcat(s1,s2);
    printf("Strings concatenated\n");
    printf("%s",s1);
    return 0;
}
void strcat(char *s, char *t)
{   
    while(*s++)
       ;
    while(*s++ = *t++)
               ;
}

I know i have done something(or many things) terribly wrong. Because whenever i try to run this code- it gives me segmentation fault. Like this-

Enter the first string

Hello

Enter the second string

Segmentation fault (core dumped)

It would be really helpful if someone points me out the flaw/flaws of my implementation. Thanks in advance.

Thank you very much guys, for such quick responses. But seems that wasn't the only problem. After writing the program like this-

#include<stdio.h>
void strcat(char *s, char *t);
int main()
{
    char s1[20], s2[20];
    printf("enter the first string\n");
    scanf("%s",s1);
    printf("Enter the second string\n");
    scanf("%s",s2);
    strcat(s1,s2);
    printf("Strings concatenated\n");
    printf("%s",s1);
    return 0;
}
void strcat(char *s, char *t)
{   
    while(*s++)
        ;
    while(*s++ = *t++)
        ;
}

It runs like this.

Enter the first string

Hello

Enter the second string

There

Hello

It only prints the first string i have entered. Now i think i have made some mistake on that strcat function too.

4

2 回答 2

11

1) 在 中main(),您必须为s1s2指针分配内存

char *s1=malloc(100*sizeof(char)), *s2=malloc(100*sizeof(char));
scanf("%99s",s1); //the "%99s" allow to avoid buffer overflow

如果您使用 gcc 并且您的 gcc>2.7,那么您可以通过scanf()以下方式使用“%ms”:

scanf("%ms",&s1);

使用"%ms",scanf()将为s1指针分配内存

s--2 )你必须添加

while(*s++)
    ;
s--; // add s-- here
while(*s++ = *t++)
    ;

因为 s 指针指向 element 的下一个'\0'元素。s 指针应该'\0'在开始复制第二个字符串之前指向元素

于 2013-08-23T08:26:42.927 回答
7

您不为s1, s1(或用数组初始化)分配内存,两者的值 s1都是s1垃圾。

char *s1, *s2;
printf("enter the first string\n");
scanf("%s",s1);

这会导致未定义的行为。

建议使用:

#define SIZE  1024
char s1[SIZE], s2[SIZE];

或使用 calloc()/maloc() 函数动态分配内存:

char *s1, *s2;
s1 = malloc(SIZE);
s2 = malloc(SIZE);

s1最近在使用,完成工作时显式地释放了内存s2

scanf() 另外,不要使用不安全的fgets()功能来避免缓冲区溢出错误。读读一行使用scanf()不好?

于 2013-08-23T08:27:01.720 回答