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