c++ - Deallocating memory -
for project have implement bitset class. code far is:
header file
#ifndef bitset_h_ #define bitset_h_ #include <string> #include <cmath> using namespace std; // container class hold , manipulate bitsets class bitset { public: bitset(); bitset(const string); ~bitset(); // returns size of bitset int size(); // sets bitset equal specified value void operator= (const string); // accesses specific bit bitset bool operator[] (const int) const; private: unsigned char *bitset; int set_size; // sets bitset equal specified value void assign(const string); }; #endif /* bitset_h_ */
source file
#include "bitset.h" bitset::bitset() { bitset = null; } bitset::bitset(const string value) { bitset = null; assign(value); } bitset::~bitset() { if (bitset != null) { delete[] bitset; } } int bitset::size() { return set_size; } void bitset::operator= (const string value) { assign(value); } bool bitset::operator[] (const int index) const { int offset; if (index >= set_size) { return false; } offset = (int) index/sizeof(unsigned char); return (bitset[offset] >> (index - offset*sizeof(unsigned char))) & 1; } void bitset::assign(const string value) { int i, offset; if (bitset != null) { delete[] bitset; } bitset = new unsigned char[(int) ceil(value.length()/sizeof(unsigned char))]; (i = 0; < value.length(); i++) { offset = (int) i/sizeof(unsigned char); if (value[i] == '1') { bitset[offset] |= (1 << (i - offset*sizeof(unsigned char))); } else { bitset[offset] &= ~(1 << (i - offset*sizeof(unsigned char))); } } set_size = value.length(); }
my problem delete statements in both deconstructor , assign method core dump. not necessary deallocate memory? i've read far it's necessary use delete command whenever call new.
edit: i've changed code above reflect 1 of fixes. added bitset = null in constructor. fixed core dump in assign method i'm still getting errors in deconstructor.
i think should initialize bitset
null
in second constructor.
why?
because pointer variable won't initialized null
. may trying delete[]
random memory address when use second constructor.
so should have:
bitset::bitset(const string value) : bitset(null) { assign(value); }
Comments
Post a Comment