C++编程思想 4.1一个袖珍的C库例题

C++编程思想
4.1一个袖珍的C库例题:
//:CLib.h
typedef struct CstashTag {
int size;
int quantity;
int next;
unsigned char* storage;
}Cstash;

void initialize(Cstash* s, int size);
void cleanup(Cstash* s);
int add(Cstash* s, const void* element);
void* fetch(Cstash* s, int index);
int count(Cstash* s);
void inflate(Cstash* s, int increase);

//:CLib.cpp{o}
#include"CLib.h"
#include
#include
using namespace std;
const int increment = 100;

void initialize(Cstash* s, int sz) {
s->size = sz;
s->quantity = 0;
s->storage = 0;
s->next = 0;
}

int add(Cstash* s, const void* element){
if (s->next >= s->quantity)
inflate(s, increment);
int startBytes = s->next * s->size;
unsigned char* e = (unsigned char*)element;
for (int i = 0; i < s->size; i++)
s->storage[startBytes + i] = e[i];
s->next++;
return(s->next - 1);
}

void* fetch(Cstash* s, int index) {
assert(0 <= index);
if (index >= s->next)
return 0;
return &(s->storage[index * s->size]);
}

int count(Cstash* s) {
return s->next;
}

void inflate(Cstash* s, int increase) {
assert(increase > 0);
int newQuantity = s->quantity + increase;
int newBytes = newQuantity*s->size;
int oldBytes = s->quantity*s->size;
unsigned char* b = new unsigned char(newBytes);
for (int i = 0; i < oldBytes; i++)
b[i] = s->storage[i];
delete ;
s->storage = b;
s->quantity = newQuantity;
}

void cleanup(Cstash* s) {

if (s->storage != 0) {
    cout << "释放存储"<< endl;
    delete []s->storage;
}

}

//:CLibTest.cpp
//{L}CLib.cpp
#include"CLib.h"
#include
#include
#include
#include

using namespace std;
int main() {
Cstash intStash, stringStash;
int i;
char* cp;
ifstream in;
string line;
const int bufsize = 80;
initialize(&intStash, sizeof(int));
for (i = 0; i < 100; i++) //sign
add(&intStash, &i);
for (i = 0; i < count(&intStash); i++) {
cout << "fetch(&intStash)," << i << ") = "
<< (int)fetch(&intStash, i)
<< endl;
}
initialize(&stringStash, sizeof(char)*bufsize);
in.open("CLibTest.cpp");
assert(in);
while (getline(in, line))
add(&stringStash, line.c_str());
i = 0;
while ((cp = (char*)fetch(&stringStash, i++)) != 0)
cout << "fetch(&stringStash)," << i << " ) = "
<< cp << endl;
cleanup(&intStash);
cleanup(&stringStash);
}

直接编译运行 提示 :
0x00000000779D0901 (ntdll.dll) (Project1.exe 中)处有未经处理的异常: 0xC0000005: 读取位置 0x000000C237E24208 时发生访问冲突。
后来发现是 sing 处的问题 那行注释掉就可以了
请问是什么原因

但是运行时在执行 cleanup(&stringStash);的时候又出现了问题 直接卡住了
只有intStash 成功释放了
请问到底是什么原因

小白希望大家多多帮助谢谢
#include<>包含的头文件显示不出来不知道为什么请大家见谅

3个回答

void inflate(Cstash* s, int increase) {
assert(increase > 0);
int newQuantity = s->quantity + increase;
int newBytes = newQuantity*s->size;
int oldBytes = s->quantity*s->size;
unsigned char* b = new unsigned char[newBytes];//这里要 new char[size] 不是new char(size)
for (int i = 0; i < oldBytes; i++)
b[i] = s->storage[i];
delete ;
s->storage = b;
s->quantity = newQuantity;
}

kanlian4095
kanlian4095 按照你说的可以正常运行了 十分感谢
接近 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!