-3

when I run this code I always found a problem in my IDE. Can you give this solution ?

#include<stdio.h>
#include<string.h>
int main(void)
{
   char cname[4]="mahe";
   strcat(cname, "Karim");
   printf("%s",cname);
   getch();
   return 0;
}
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
Mahe Karim
  • 49
  • 1
  • 10
  • 1
    What is the problem you found? what is the error message? Please take some time to visit the [help center](http://stackoverflow.com/help) and also read [How to Ask](http://stackoverflow.com/help/how-to-ask), [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve), so you can learn what types of questions are accepted here, how to write questions, and how to use this site effectively – Sourav Ghosh Mar 25 '17 at 05:45

2 Answers2

2

Your array isn't big enough. The original array isn't big enough to hold the null byte at the end of its initial value, so strcat() can't find the end of the string. And then you're adding to it, which writes outside the array. These are both causing undefined behavior.

It needs to be declared large enough to hold the original string, the string you're adding to it, and the trailing null byte. So it has to be at least 10 bytes (4+5+1).

char cname[10] = "mahe";
strcat(cname, "Karim");
printf("%s\n", cname);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Change char cname[4] to char cname[10]. Because you are setting the size 4 and so, you can't append any more to it after adding 4 chars initially.

So, change the size. That's it

Sagar V
  • 12,158
  • 7
  • 41
  • 68