Let's take an example.
#include <stdio.h>
#include <string.h>
int main() {
char str1[7] = "hello ";
printf("Initial size of str1 is: %d\n", strlen(str1));
char str2[] = "buddy";
printf("%s\n", strcat(str1, str2));
printf("Final size: %d\n", strlen(str1));
}
The output of the above program will be
Initial size of str1 is: 6
hello buddy
Final size: 11
--------------------------------
Process exited after 0.835 seconds with return value 0
Press any key to continue . . .
See? how the size of str1
changed from 7 to 11 (including null variable), regarding that what I think would have happened is :
str1
starting from same address as before i.e str1
with size strlen(str1)+strlen(str2)+1
+1 for null value, and then redefined it to get hello buddy.If I am wrong please tell, if not then, what function is it and how does it work?
One more question: how can I write a code to do the above task without the use of strcat
function.
I tried doing it using realloc()
but didn't quite succeed may be that's because realloc()
can only reallocate dynamically allocated memory, is it so?
Buffer overflow
OP's code fails as strcat(str1,str2)
attempts to write past the end of str1[]
- result: undefined behavior (UB). @dimich
Instead use a larger destination buffer.
// char str1[7]="hello ";
char str1[7 + 5]="hello ";
char str2[]="buddy";
printf("%s\n",strcat(str1,str2));
Use correct print specifier
strlen()
returns a size_t
, not an int
.
// printf("Initial size of str1 is: %d\n",strlen(str1));
printf("Initial size of str1 is: %zu\n",strlen(str1));
Tip: enable all warnings.
Alternative
One of many alternatives: copy str2
to the end of str1
.
// printf("%s\n",strcat(str1,str2));
strcpy(str1 + strlen(str1), strt2);
printf("%s\n",str1);
realloc()
realloc()
can only reallocate dynamically allocated memory, is it so?
realloc()
should not be used on pointers to non-allocated, non-NULL
pointers.
In addition to re-allocating dynamically allocated memory, realloc()
can start with no prior allocation.
char *p = realloc(NULL, size);
// just like
char *p = malloc(size);
Moral of the story