我用谷歌搜索了大约2个小时修复此错误。 我收到以下错误:“运行时检查失败#2 - 变量'缓冲区'周围的堆栈已损坏。”
我知道它必须对我的指针,我的sprintf_s函数或类似函数做一些事情。这个简单的程序应该只用','
替换'-'
。
我希望有人可以给我一些解决方法。我知道存在很多这样的问题,但没有一个能帮助我解决这个错误。
#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;
}
答案 0 :(得分:1)
当您致电sprintf_s()
时,您将从buffer
的中间开始。因此,您需要减少该索引的可用空间。它应该是:
sprintf_s(buffer + (p - source), sizeBuffer - (p - source), "%s%s", replace, p + strlen(substring));