koushik
koushik

Reputation: 1

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

#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

Upvotes: 0

Views: 116

Answers (2)

Seffih Oualid Redouan
Seffih Oualid Redouan

Reputation: 53

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

Upvotes: 0

Md. Faisal Habib
Md. Faisal Habib

Reputation: 1116

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);
}

Upvotes: 1

Related Questions