-5

I have a problem when use strcat function. I have no idea.please help me.thanks

char dst[5]="hello";
char *a = "12345";
char *b = "54321";

//work
strcat(strcpy(dst, a), b);
printf("one==%s\n",dst);

//error
strcpy(dst, a);
strcat(dst, b);
printf("two==%s\n",dst);
cowry chen
  • 11
  • 1

3 Answers3

1

The problem with both versions is that you are writing past the end of dst. Both a and b require six bytes including the NUL terminator; dst only has space for five.

This results in undefined behaviour.

The nature of undefined behaviour is such that it may or may not manifest itself. If it does, it could be in fairly arbitrary ways.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

You dont allocate correctly your memory on your dst pointer, here is a working code:

int             main()
{
  char *dst;
  char *a = strdup("12345");
  char *b = strdup("54321");

  dst = malloc(100);
  dst = strdup("hello");                                                                             
strcat(strcpy(dst, a), b);
printf("one==%s\n",dst);                                                                                
strcpy(dst, a);
strcat(dst, b);
printf("two==%s\n",dst);
}
Saxtheowl
  • 4,136
  • 5
  • 23
  • 32
  • When dealing with `char`, it is unnecessary to have `(sizeof (*dst))`; the C standard explicitly defines the size of `char` as 1. – verbose Aug 21 '13 at 08:20
0

PROGRAM:

#include<string.h>
#include<stdio.h>

int main()
 {
        char dst[15]="hello";
        char *a = "12345";
        char *b = "54321";

        //work
        strcat(strcpy(dst, a), b);
        printf("one==%s\n",dst);

        //error
        strcpy(dst, a);
        strcat(dst, b);
        printf("two==%s\n",dst);
        return 0;
    }

OUTPUT:

# 1:   hide   clone   input   8 seconds ago
result: success      time: 0s    memory: 2684 kB     returned value: 0

input: no
output:
one==1234554321
two==1234554321

EDIT: Instead of 15 you can use 11 as well.. hope you understood the purpose of your code..

Abhishek
  • 874
  • 2
  • 8
  • 23