一个内存溢出问题,在注释处显示出写入S.ch时缓冲区溢出,我不知道为什么。我的环境是VS2022.请问是怎么回事呢?
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <assert.h>
#include <string>
#define OK 1
#define ERROR 0
//#define OVERFLOW -2
//#define MAXLEN 40
typedef int Status;
using namespace std;
typedef struct
{
char* ch;
int length;
}HString;
Status StrAssign(HString& T, char* chars)
{
int i = 0;
if (!chars)
{
cout << "The string chars passed in is invalid." << endl;
return ERROR;
}
while (chars[i++]);
if (!(i - 1) || T.ch)
{
delete[]T.ch;
T.length = 0;
}
else
{
if (!(T.ch = new char[i])) exit(OVERFLOW);
strcpy(T.ch, chars);
T.length = i - 1;
}
return OK;
}
Status StrInsert(HString& S, int pos, HString T)
{
assert(S.ch && T.ch);
if (pos < 1 || pos > S.length + 1) return ERROR;
int i;
if (!T.length) return OK;
else
{
//if (S.ch) delete[]S.ch;
char* ptr = (char*)realloc(S.ch, (S.length + T.length) * sizeof(char));
if (NULL == ptr) exit(OVERFLOW);
S.ch = ptr;
for (i = S.length - 1; i >= pos - 1; i--)
S.ch[i + T.length] = S.ch[i];
for (i++; i <= pos - 1 + T.length - 1; i++)
S.ch[i] = T.ch[i - pos + 1];// 这里显示出写入S.ch时缓冲区溢出,我不知道为什么。
S.ch[S.length + T.length] = '\0';
return OK;
}
}
Status StrPrint(HString S)
{
assert(S.ch);
cout << "The following is the content of t\
he string of heap sequential storage structure: "
<< endl;
cout << S.ch << endl;
cout << "The following is the length of the string :"
<< endl << S.length << endl;
return OK;
}
Status ClearString(HString& S)
{
if (S.ch) {
delete[]S.ch;
S.ch = NULL;
}
S.length = 0;
return OK;
}
int main(void)
{
char a[50] = { "I have a friend. You have. He have." };//16 a friend. You have. He have.*//
char c1[10] = { "ev" };
HString S, S0, S1;
S.ch = NULL;
S1.ch = NULL;
StrAssign(S, a);
StrAssign(S1, c1);
StrInsert(S, 7, S1);
StrPrint(S);
ClearString(S);
ClearString(S1);
return 0;
}
char* ptr = (char*)realloc(S.ch, (S.length + T.length + 1) * sizeof(char));// 原串和新增子串长度相加
if (NULL == ptr) exit(OVERFLOW);
S.ch = ptr;
for (i = S.length - 1; i >= pos - 1; i--)
S.ch[i + T.length] = S.ch[i];
for (i++; i <= pos - 1 + T.length - 1; i++)
S.ch[i] = T.ch[i - pos + 1];// 这里已经修改,不会出现缓冲区溢出。
S.ch[S.length + T.length] = '\0';
第一行relloc