0
Follow
0
View

What's wrong with experiment 9, 3149

ddza888 注册会员
2023-02-28 20:18
  • Use the gets() function cautiously. The gets() function is not very secure. It does not check the length of the input string and may cause a buffer overflow. You can use the fgets() function instead of

  • Your Strcat input string is best to use const char. You don't change the input string.

  • Boundary handling problem

#include 
#include 
#include 

void Strcat(char* dest, const char* src);

int main()
{
    char str1[200];
    char str2[100];
    fgets(str1, sizeof(str1), stdin);
    fgets(str2, sizeof(str2), stdin);
    Strcat(str1, str2);
    printf("%s", str1);
    return 0;
}

void Strcat(char* dest, const char* src)
{
    // 将指针移动到目标字符串的末尾
    while (*dest != '\0')
    {
        dest++;
    }
    
    // 将源字符串复制到目标字符串中
    while (*src != '\0')
    {
        // 检查缓冲区溢出
        if (dest >= (dest + sizeof(dest) - strlen(src) - 1))
        {
            fprintf(stderr, "Error: Destination string overflow\n");
            exit(EXIT_FAILURE);
        }
        
        *dest = *src;
        dest++;
        src++;
    }
    
    // 在字符串末尾添加空字符
    *dest = '\0';
}


deathcj 注册会员
2023-02-28 20:18

Remove the s-- and modify it as follows:

#include 
#include 
// write your code here
void Strcat(char *s1, char *s2);
int main()
{
    char str1[200];
    char str2[100];
    gets(str1);
    gets(str2);
    Strcat(str1, str2);
    return 0;
}
void Strcat(char *s1,char *s2)
{   
    char *s=s1;
    while(*s1!='\0')
       s1++;
    // s1--;
    while((*s1=*s2)!='\0')
    {
        s1++;
        s2++;
    }
    printf("%s\n",s);
}
dadmy3652013 注册会员
2023-02-28 20:18
< div class = " md_content_show“数据- v - 3967 e397 = " " >

< div class = " aw-list-img " > img

dandan1980 注册会员
2023-02-28 20:18

Please see the comments for the changes:

#include 
#include 
// write your code here
void Strcat(char *s1, char *s2);
int main()
{
    char str1[200];
    char str2[100];
    gets(str1);
    gets(str2);
    Strcat(str1, str2);
    printf("%s\n",str1); //修改

    return 0;
}
void Strcat(char *s1,char *s2)
{   char *s=s1;
    while(*s1!='\0')
      s1++;
    //s1--;       修改
    while((*s1=*s2)!='\0')
     {s1++;s2++;}
    *s1='\0';   //修改
    //printf("%s\n",s); 修改
}

About the Author

Question Info

Publish Time
2023-02-28 20:18
Update Time
2023-02-28 20:18