Home > Mobile >  I got issue in strcpy in C, is there any mistake in my code?
I got issue in strcpy in C, is there any mistake in my code?

Time:08-28

#include<stdio.h>
#include<string.h>
int main(){
char oldS[] = "Hello";
char newS[] = "Bye";
strcpy(newS, oldS);
puts(newS); 
}

I was trying to learn string.h in C, will doing strcpy I am unable to get the output. output is like

koushik@Koushiks-MacBook-Air C % cd "/Users/koushik/Documents/
C/" && gcc stringcopy.c -o stringcopy && "/Users/koushik/Docum
ents/C/"stringcopy
zsh: illegal hardware instruction "/Users/koushik/Documents/C/"stringcopy

CodePudding user response:

When you use strcpy(), the size of the destination string should be large enough to store the copied string. Otherwise, it may result in undefined behavior.

As you've declared the char array without specifying the size, it was initialized with the size of the string "Bye", which is smaller than the string "Hello". That's why problem occurred.

Solution:

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

int main() 
{
    char oldS[6] = "Hello";
    char newS[6] = "Bye";
    strcpy(newS, oldS);
    puts(newS);
}

CodePudding user response:

You need to allocate space to use strcpy either way with creating an array with a suffisent size or using malloc

  •  Tags:  
  • c
  • Related