Please check the following program:
Code:
#include<stdio.h>
#include<string.h>
int main(void){
char nameB[]="Jerry";
char nameA[]="Tom";
printf("\n nameA: %s",nameA);
printf("\n nameB: %s",nameB);
strncpy(nameA,nameB,4);
printf("\n nameA: %s",nameA);
printf("\n nameB: %s",nameB);
printf("\n");
return 0;
}
Output is following:
Code:
nameA: Tom
nameB: Jerry
nameA: JerrJerry
nameB: Jerry
Any idea why this strange result is coming? I think buffer overflow is a reason for it because the string nameA contains only 3 characters but the strncpy function copied 4 characters in it.
If it is the case, then I expect a random output from the memory/other errors but here the output for nameA is JerrJerry which suggests the first 4 characters of nameB is copied successfully and nameB is printed again. Any clue?
The output changes when I change the order of 5th and 6th line in the same program.
Code:
#include<stdio.h>
#include<string.h>
int main(void){
char nameA[]="Tom";
char nameB[]="Jerry";
printf("\n nameA: %s",nameA);
printf("\n nameB: %s",nameB);
strncpy(nameA,nameB,4);
printf("\n nameA: %s",nameA);
printf("\n nameB: %s",nameB);
printf("\n");
return 0;
}
Logically, there should be no reason for a different type of result but the following output comes:
Code:
nameA: Tom
nameB: Jerry
nameA: JerrH "
nameB: Jerry
Now, it looks like a random result is generated for NameA for buffer overflow. But here also, first 4 characters are copied which should not happen.
What is the reason of strange result of case 1 & 2 and why for the same program, different output is coming? I am using Codeblock with MinGW compiler.
Any help will be highly appreciated!