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
getprefix in e.g.get_sizejava-ism.
in c++getprefix has no advantage, , makes code less readable. example, standard library containers havesizemethod, notget_size.using
voidformal 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
constversion 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 uppercaseidentifiers constants java-ism.
java lacks preprocessor, , inherited uppercase convention c, lackedconst. c++ has bothconst, preprocessor. havingconstthere's no need use#defineconstants (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
exceptionshould 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_errordirectly.
Comments
Post a Comment