Heap corruption I don't know where and why it's coming from.

Asked 2 years ago, Updated 2 years ago, 40 views

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;
}

c strcpy

2022-09-20 18:06

1 Answers

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.


2022-09-20 18:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.