0

our first string is 6 bytes,and using memcpy func we are copying second string into first more than 6bytes still its working.How

our first string is 6 bytes,and using memcpy func we are copying second string into first more than 6bytes still its working.How? just watch this code #include <stdio.h> #include<string.h> int main() { char str1[6]="sandip"; char str2[]="qwertyuio"; memcpy(str1,str2,sizeof(str2)); printf("%s",str1); } op:qwertyuio

18th Aug 2022, 6:20 PM
Sandip Doke
5 Réponses
+ 1
I didn't really understand the question but I think the problem has to do with the memcpy Try this code, look at the result so you properly understand the memcpy and you can change the value to any number char L[] = "ABC"; memcpy(L, "abc", 1); printf("%s", L);
18th Aug 2022, 8:07 PM
SoloProg
SoloProg - avatar
0
Is it the same question as here? https://www.sololearn.com/Discuss/3074386/?ref=app Please do not re-post the same question.
18th Aug 2022, 6:29 PM
Lisa
Lisa - avatar
0
I can't get my answer
18th Aug 2022, 6:32 PM
Sandip Doke
0
If someone knows how it works, they will answer. Please don't post duplicates. All other users on Q&A are regular users just like you. They will answer when they have time and interest.
18th Aug 2022, 6:43 PM
Lisa
Lisa - avatar
0
It overwrites some memory on the stack that apparently doesn't cause visible damage, but if str2 were longer, it would crash. To see that it overwrites, try this: #include<stdio.h> #include<string.h> int main() { char str0[]="hello!"; char str1[6]="sandip"; char str2[]="123456789012"; printf(str1); memcpy(str1,str2,sizeof(str2)); printf("\n%s\n%s", str1, str0); } You'll first see that declaring a string of 6 characters can actually only hold 5 characters + the terminal NULL (character '\0'). Since you put 6 characters, the terminal \0 will be outside, encroaching on the memory of str0, which will overwrite it (bc apparently variables are placed on stack in the reverse order that they are declared). Displaying str1 will appear longer bc it actually displays until it finds the terminal \0, which now happens beyond str1 - it happens at the end of str0. But when you try to put into str1 more than it can hold, it will overwrite str0.
18th Aug 2022, 9:17 PM
lion
lion - avatar