Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does strcpy trigger an error?

Tags:

c

The program works fine if the string is not copied using strcpy, but I would like to know the reason why ?

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

int main ()
{

    int mat;
    char test1[20]={"Hex"} ;
    char test2[20]={"agonal"} ;

    strcpy(test1,"Diagonal"); // the print outputs the concatenated test if strcpy is commented out

    //printf("a=%c\nb=%c\n",test1[0],test1[1]);

    printf("Concatenated test=%s", strcat(test1, test2));

    return 0;
}


ERROR MESSAGE

*** buffer overflow detected ***: ./prog terminated
      ======= Backtrace: =========
      /lib/libc.so.6(__fortify_fail+0x48)[0xb75b6ae8]
      /lib/libc.so.6[0xb75b4b30]
      /lib/libc.so.6[0xb75b3dcd]
     ./prog(__gxx_personality_v0+0x14d)[0x804858d]
     ./prog(__gxx_personality_v0+0x31)[0x8048471]
      ======= Memory map: ========
like image 301
Borrito Avatar asked Jun 01 '26 12:06

Borrito


1 Answers

The strcat call is the one failing. You don't have enough space in test1 to store the concatenation of "Diagonal" and "agonal".

If you make test1 big enough, it should work:

char test1[40]={"Hex"} ;
like image 103
Pablo Santa Cruz Avatar answered Jun 04 '26 00:06

Pablo Santa Cruz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!