I'm trying to copy a string of characters in another string using dynamic memory allocation but it doesn't work:
#include <stdlib.h>
#include <stdio.h>
int main() {
char* s1, * s2, * s3;
s1 = (char*)malloc(11 * sizeof(char));
s2 = (char*)malloc(11 * sizeof(char));
s3 = (char*)malloc(11 * sizeof(char));
fgets(s1, 11, stdin);
fgets(s2, 11, stdin);
int i = 0;
do {
*(s3 i) = *(s1 i);
i ;
} while (*(s1 i) != '\n' && *(s1 i) != '\0');
puts(s3);
return 0;
}
CodePudding user response:
You do not null terminate the s3
string.
} while (*(s1 i) != '\n' && *(s1 i) != '\0');
s3[i] = 0;
puts(s3);
CodePudding user response:
You have a bug here: } while (*(s1 i) != '\n' && *(s1 i) != '\0');
.
This means that you stop copying at \n
which fgets
will place in the buffer but you do not null terminate the string s3
.
So if s1
looks like "hello\n\0"
then s3
will end up as "hello\n"
without null terminator.
Corrected and de-obfuscated loop:
size_t i;
for(i=0; s1[i]!='\n' && s1[i]!='\0'; i )
{
s3[i] = s1[i];
}
s3[i] = '\0';