strcpy and strcat

str.c

I see that some people tend to use strcat() immediately, without using strcpy() at all. We should first use strcpy() and then strcat(). Check the examples below to see why. 🙂

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

int main(void)
{
        char buf[30];
        strcat(buf, "hello");
        strcat(buf, " ");
        strcat(buf, "world!");
        printf("%s\n", buf);
        return 0;
}

This will output (if it doesn’t crash), in my pc

������V���m�%�V��Rp�hello world!

In other words, undefined behavior!
Now, here is a working piece of code.

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

int main(void)
{
        char buf[30];
        strcpy(buf, "hello"); // Use of strcpy!!!
        strcat(buf, " ");
        strcat(buf, "world!");
        printf("%s\n", buf);
        return 0;
}

This will output

hello world!

This code was developed by me, G. Samaras.

Have questions about this code? Comments? Did you find a bug? Let me know! 😀
Page created by G. (George) Samaras (DIT)

Leave a comment