Question

I defined the size of target as size of string1. Then I added string2 to target. I didn't increase the size of my target. Why does my still code work?

char *string1 = "this is a ";
char *target = malloc(sizeof(string1)); // if i don't do this, code gives error.
strcpy(target, string1);
printf("%s\n", target);

char *string2 = "string";
strcat(target, string2); // how come I don't need to call malloc again?
printf("%s\n", target); // works

I compiled this with Xcode on mac.

Was it helpful?

Solution

It works because you're lucky. Writing past the end of a buffer is a good way to damage the data following that buffer and cause your program to blow up in nasty ways.

Actually you were lucky even the first time. Sizeof returns the size of the variable's type, which is a pointer, NOT the length of the string. And even if you'd used strlen(string1) you'd have to also add 1 to allow space for the null character which terminates the string.

C will let you shoot your own feet off. It's your responsibility to make sure you don't, and/or to run additional tests on your code using tools like lint to catch some of the errors other languages always check for. (Or run your compiler at higher warning levels.)

On the flipside, being able to cheat in C when you really do want to is one of the things which makes it powerful -- like assembler code, if you know what you're doing, you can break the rules to do things that would otherwise be difficult to impossible. It's a sharp knife. Be careful to know what's around you in case it slips.

OTHER TIPS

Some issues in your code.

  1. What do you think sizeof(string1) should return? Have you tried that? Do you know the difference between sizeof() and strlen() ? By the way, sizeof(string1) will return the size in bytes of a pointer to a char, usually 4 bytes.

  2. Check the strcat() documentation

"destination:Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string."

If it "works" a couple of times, does not mean the code is correct. You have to understand that you are writing information in a piece of memory that you didn't allocate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top