Segmentation fault: 11 ? C++ -
can tell why generate segmentation error? problem seems occur when operator[] called , when don't call it, goes fine. operator[] supposed return reference element index i.. great..
//dynamic_array.cpp file #include <iostream> #include "dynamic_array.h" using namespace std; dynamic_array::dynamic_array() { int *array; array=new int[4]; array[0]=3; size = 4; allocated_size = 5; } dynamic_array::~dynamic_array() { delete [] array; } int dynamic_array::get_size(void) const { return size; } int dynamic_array::get_allocated_size(void) const { return allocated_size; } int& dynamic_array::operator[](unsigned int i) { return array[i]; } //test.cpp file #include <iostream> #include <stdlib.h> #include "dynamic_array.h" using namespace std; int main() { dynamic_array a; cout << a[0]; } //dynamic_array.h file using namespace std; class dynamic_array { public: enum { block_size = 5, subscript_range_exception = 1, memory_exception = 2, }; dynamic_array(); ~dynamic_array(); int get_size(void) const; int get_allocated_size() const; int& operator[](unsigned int i); class exception { public: exception(int n0) { n = n0; }; int n; }; private: int *array; // pointer dynamically allocated memory int allocated_size; // total number of elements in allocated memory int size; // number of active elements };
the local declaration
int *array;
shadows member array
. following code uses local variable, not member. hence member uninitialized.
instead of creating own dynamic array, use std::vector
.
that's safer , more convenient.
in other news:
the
get
prefix in e.g.get_size
java-ism.
in c++get
prefix has no advantage, , makes code less readable. example, standard library containers havesize
method, notget_size
.using
void
formal argument declaration, inget_size(void)
, c-ism.
in c has important effect of telling compiler there no arguments, opposed arguments. in c++()
indicates that.not having
const
version ofoperator[]
inconsistent earlier use ofconst
.
consistency important in programming. our expectation, e.g. when maintaining code, it's consistent. code that's inconsistent adds costly man-hours maintenance.the
all uppercase
identifiers constants java-ism.
java lacks preprocessor, , inherited uppercase convention c, lackedconst
. c++ has bothconst
, preprocessor. havingconst
there's no need use#define
constants (as in c), , having preprocessor there's tecnical reason not use uppercase (it conflicts convention macro names). in addition many/most programmers see uppercase shouting. hurts.the class
exception
should better derivedstd::exception
.
instead of inventing one's own exception class can carry error code, usestd::system_error
. that's it's for. alternatively, derive classstd::runtime_error
, or usestd::runtime_error
directly.
Comments
Post a Comment