0

i searched alot with google and spend about 2 hours fixing this error. I get the following Error:
"Run-Time Check Failure #2 - Stack around the variable 'buffer' was corrupted."

I know it has to do something with my pointers, my sprintf_s functions or similar. This simple program is supposed to just replace ',' with '-'.

I hope someone can give me a hint to solve this. I know a lot of those questions exist but none of them helped me fix this error.

#include "stdafx.h"
#include <stdio.h>

int strReplace(char *buffer, const rsize_t sizeBuffer,
    char *source, const rsize_t sizeSource,
    const char *substring, const rsize_t sizeSubstring,
    const char *replace, const rsize_t sizeReplace)
{
    if (sizeBuffer < sizeSource || sizeBuffer < sizeReplace || sizeSource < sizeSubstring)
        return -1;

    char *p;

    p = strstr(source, substring);
    while (p != NULL)
    {
        strncpy_s(buffer, sizeBuffer, source, p - source);

        buffer[p - source] = '\0';

        sprintf_s(buffer + (p - source), sizeBuffer, "%s%s", replace, p + strlen(substring));

        strncpy_s(source, sizeSource, buffer, sizeBuffer);
        p = strstr(source, substring);
    }

    return 0;
}

int myFunc(char *source, const rsize_t sizeSource)
{
    char *substring = ",";
    char *replace = "-";
    char buffer[100];

    strReplace(&buffer, 100, source, sizeSource,
        substring, 2, replace, 2);

    return 0;
}

int main()
{
    char input[25] = "1,2,3,4,5,6,7,8,9,0";

    printf("input: %s\n", input);
    myFunc(&input, 25);

    _getch();

    return 0;
}
8
  • You should step through the strReplace() function in the debugger, and examine the variables after each step. Commented Dec 21, 2017 at 0:05
  • @Barmar already did that following every variable. Had no luck with that. Maybe i'm doing something wrong there Commented Dec 21, 2017 at 0:07
  • I don't think it should cause a problem, but sizeBuffer should be sizeBuffer-(p-source) in the sprintf_s() call. Commented Dec 21, 2017 at 0:10
  • Many implementations of string replacement can be found here Commented Dec 21, 2017 at 0:12
  • @Barmar no that's okay. It is supposed to append the buffer. Commented Dec 21, 2017 at 0:14

1 Answer 1

1

WHen you call sprintf_s(), you're starting from the middle of buffer. So you need to reduce the available space by that index. It should be:

    sprintf_s(buffer + (p - source), sizeBuffer - (p - source), "%s%s", replace, p + strlen(substring));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.