我正在研究一个简单的向量程序作为作业,但我无法弄清楚我为什么程序断言。我的程序编译成功,但在运行时失败。我认为我已经掌握了这方面的专业知识。
#include <iostream>
#include <cstring>
#include <assert.h>
#include <stdio.h>
#include <iomanip>
#define TESTING
using namespace std;
typedef float Elem;//floats for vector elements
struct Vector{//structure for the vector
unsigned int size;
Elem *svector;
};
int main(){
#ifdef TESTING
//prototypes
Vector *alloc_vec();
bool print_vec(Vector *printVector);
Vector *extend_vec(Vector *extend,Elem element);
Vector *scalar_plus(Vector *vecToAdd, Elem addElement);
void dealloc_vec(Vector *&deAlloc);
//testing scaffolds
Vector *testVec=new Vector;
*testVec=*alloc_vec();
assert(testVec->size==0);
assert(testVec->svector==NULL);
for(int i=0;i=10;i++){
*testVec=*extend_vec(testVec,Elem(i));
}
assert(testVec->size!=0);
assert(testVec->svector!=NULL);
assert(print_vec(testVec));
print_vec(testVec);
*testVec=*scalar_plus(testVec,5);
print_vec(testVec);
dealloc_vec(testVec);
assert(testVec==NULL);
#endif //testing
return 0;
}
Vector *alloc_vec(){//constructor to allocate an empty (zero-length) vector
Vector *newVector=new Vector; //initiatizes a new vector
if (newVector==NULL){
return NULL;
}
newVector->size=0;//sets length to 0
newVector->svector=NULL;//sets vector to null
return newVector;
}
bool print_vec(Vector *printVector){
if(printVector==NULL){//makes sure printVector exists to pass unit test 1
return false;
}
for(unsigned int i=0; i<printVector->size;i++){
cout<<printVector->svector[i]<<endl;
}
return true;
}
void dealloc_vec(Vector *deAlloc){
if (deAlloc==NULL){//if the vector contains no memory, no need to deallocate, unit test#1
return;}
delete deAlloc;//clears the memory of the vector
deAlloc=NULL;
return;
}
Vector *extend_vec(Vector *extend,Elem element){
if (extend==NULL){
return NULL;}
Elem *tempVec=new Elem[extend->size+1];//sets up a temp vector one size larger
tempVec[extend->size]=element;
memcpy(tempVec,extend->svector,(extend->size*sizeof(Elem)));//copies the memory from the original array to the rest of the temp array
extend->size+=1;
delete[] extend->svector;//clears the memory
extend->svector=tempVec;//the original vector now becomes the extended vector
delete[] tempVec;//clears the temporary memory
return extend;
}
Vector *scalar_plus(Vector *vecToAdd, Elem addElement){
if (vecToAdd==NULL){
return NULL;}
for(unsigned int i=0;i<vecToAdd->size;i++){//adds a scalar to each element
vecToAdd->svector[i]+=addElement;
}
return vecToAdd;
}
**编辑有人问我得到了哪个断言错误:
调试断言失败!
程序:...12\Projects\ConsoleApplication2\Debug\ConsoleApplication2.exe
文件:f:\dd\vctools\crt_bld\self_x86\crt\src\dggdel.cpp
线路:52
表达式:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
我还进行了以下更改: assert(testVec=NULL) (deAlloc==NULL)
到
assert(testVec==NULL)
(deAlloc==NULL)
此函数来自:void dealloc_vec(Vector *deAlloc)
到:
void dealloc_vec(向量 *&deAlloc)
断言错误已修复,但不会产生输出。还在调试中。
此外,这很可能是 C 而非 C++。我的教授在作业规范中说这是 C++,但他在我们班的两个批次之间切换。