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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s