Question

I started learning C yesterday, so this might be a trivial question, but I still don't get this.

Let's say I have the following code:

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

int main()
{
    char text[8];
    strcpy(text, "Lorem ");
    puts(text);
    strcat(text, "ipsum!");
    puts(text);
    return 0;
}

This will result in a segmentation fault when (or after) concating the strings. However if I change the size of textfrom 8 to 9, it doesn't.

Please correct me if I'm wrong but this is what I thought was right:

"Lorem " - size 6 (or 7 with \0)
"ipsum!" - size 6 (or 7 with \0)
"Lorem ipsum!" - size 12 (or 13 with \0)

So, where does the 8/9 come from? Is this caused by the implementation of strcat? Or is there something like a minimum array length? Or am I making a stupid beginner's mistake?

Thanks in advance.

Was it helpful?

Solution

It's just pure luck that it didn't crash, at least on Linux I get *** stack smashing detected ***.

You are trying to append a string to another string even though the storage for the latter is insufficient. It is an example of undefined behaviour (as pointed out in the comments).

C is the sort of language that always trusts the programmer with what is in the program and so you may not even get a warning for this when compiling.

Always ensure that you have enough storage in your buffers, there are very few facilities in C that guarantee safe behaviour so do not assume things such as minimum array length.

OTHER TIPS

When you overrun the end of an array, the program has undefined behaviour. this means it might do what you expect it to do or it might not. It might run as if you hadn't invoked undefined behaviour. It might crash. It might reformat your hard drive. It might print a blank page on your printer. It might do all of those things depending on when you run it.

You can't know. That's what 'undefined behaviour' is. Undefined.

I could give you an explanation for the behaviour, but it'd be unhelpful, and very hardware and implementation specific.

You can malloc to whatever size you want. and even you can realloc also according to the further input.

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

int main()
{
    char *text;
    text = (char *) malloc(sizeof(char) * 12);
    memset(text, 0x0, sizeof(char) * 12);
    sprintf(text, "%s", "Lorem ");
    puts(text);
    sprintf(text, "%s%s", text, "ipsum!");
    puts(text);
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top