-1

When this code for swapping two string is being executed I get undesired outputs

    #include<bits/stdc++.h>
    using namespace std;

    int main()
    {
        char a2[] = "Hello world";
        char a1[] = "Geek";
        char a3[20];
        cout<<a2<<endl<<a1<<endl;

        strcpy(a3,a1);
        strcpy(a1,a2);
        strcpy(a2,a3);

        cout<<a2<<endl<<a1<<endl;
    }

I get these results:

Hello world

Geek

Geek

HelloGeek (I expect it to be HelloWorld)

Is there something I'm doing wrong in the code.

  • 4
    `strcpy(a1,a2);` -- Buffer overrun. `char` arrays, or any arrays, do not magically resize themselves. – PaulMcKenzie Oct 10 '18 at 03:26
  • As for what you're doing wrong in the code: You're writing C++. Why are you using C-style strings with raw arrays? – ShadowRanger Oct 10 '18 at 03:37
  • Like Paul says: The line that says `char a1[] = "Geek";` is actually saying `char a1[5] = "Geek";` and strcpy only copies character - it doesn't make the array bigger. – Jerry Jeremiah Oct 10 '18 at 03:43
  • `int a1[] = {1,2,3}; int a2[] = {4,5}; int a3[10];` -- Try and make `a2` hold 3 integers. You can't -- arrays are fixed in size, `a2` can hold 2 integers now and forever. This is no different than what you are trying now with characters. – PaulMcKenzie Oct 10 '18 at 12:45

2 Answers2

3

In your program

char a2[] = "Hello world";

defines a character array sized to fit the string literal "Hello world". It can contain 12 characters including the nul terminator.

char a1[] = "Geek";

behaves the same, but "Geek" only requires 5 characters with the nul, so the array is 5 characters long.

strcpy(a3,a1);

does what you expect, copies 4 characters of "Geek" into a3's 20 byte buffer and nul terminates.

strcpy(a1,a2);

tries to put "Hello world" into the five character array of a1. This invokes Undefined Behaviour when the buffer is overrun. Undefined Behaviour is what it sounds like, something undefined happens, so you cannot rely on any of your expectations of this program from here on. What probably happens is one of the other variables around a1 partially overwritten but the compiler would be just as correct if it produced a program that made your computer jump up and start dancing the Macarena.

user4581301
  • 33,082
  • 7
  • 33
  • 54
0

To elaborate on Paul Mc Kenzie's comment:

The memory for the strings has been statically allocated on your programs stack. E.g. the array containing 'Geek' only has space for that and the terminating null character, so you should not copy the longer string there.

I'd recommend you to use std::string instead. It handles the buffer allocations automatically and you can use = instead of strcpy.

Sami Sallinen
  • 3,203
  • 12
  • 16