Write Code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char* szBuffer = (char*)calloc(200,1);
scanf_s("%s", szBuffer,_msize(szBuffer));
int length = strlen(szBuffer);
char* szNewBuffer = (char*)calloc(10,1);
scanf_s("%s", szNewBuffer,_msize(szNewBuffer));
int length2 = strlen(szNewBuffer);
if (length + length2 >_msize(szBuffer)-1 ) {
realloc(szBuffer, length + length2);
if (szBuffer == NULL) {
printf ("assignment failure");
}
else {
printf ("Assignment Successful");
memcpy(szBuffer + length,szNewBuffer,length2);
puts(szBuffer);
}
free(szBuffer);
free(szNewBuffer);
return 0;
}
printf("%s\n", szBuffer);
printf("%s\n", szNewBuffer);
strcpy_s(szBuffer + length,_msize(szBuffer), szNewBuffer);
printf("%s", szBuffer);
free(szBuffer);
free(szNewBuffer);
return 0;
}
There is a problem with the 6th line from the bottom.
strcpy_s(szBuffer + length, _msize(szBuffer), szNewBuffer);
Change the code above as below.
strcpy_s(szBuffer + length, _msize(szBuffer) - length, szNewBuffer);
Initially, the size of the szBuffer is _msize(szBuffer), but because you wanted to paste a new string at the back of the existing string, you specified szBuffer+length
as the memory start point, so the available size is _msize(szBuffer)-length.
© 2024 OneMinuteCode. All rights reserved.