Whenever I try to run my code I get these error lines. It also seems like that sometimes it crashes the program. Is that possible or something else causes the crash?
The error code comes to these lines:
Buffer<char*> s(20,"s.txt","rw"); //20 long char*
for(unsigned int i=0;i<24;i++){ //it overwrites the size of s after default 20
s[i]="hey"; //error here: "deprecated conversion from string constant to 'char*'"
The class looks like this(deleted the unimportant parts":
template<class T>
class Buffer:public File_ptr
{
unsigned int siz;
T *data;
public:
///constructor(size,filename,openmode)
Buffer(unsigned int s,const char* n, const char* m):File_ptr(n,m),siz(s)
{
data= new T[siz];
/* for(unsigned int i=0; i<siz; ++i)
{
data[i]=0;
}; */
};
///destructor
~Buffer()
{
delete[] data;
}
///operator[]
T& operator[](unsigned int i)
{
if(i>siz-1)
{
unsigned int newsize=siz*2;
T* tmp=new T[newsize];
for(unsigned int j = 0; j < siz; j++)
{
tmp[j] = data[j];
}
siz=newsize;
delete[] data;
data=tmp;
};
return data[i];
};
Any idea why I get the error?
Thanks in advance!
"hey" is a string literal and so the compiler stores it in a different part of the executable which is likely to be stored in write-protected memory along with all other strings. As a result, in C++, in a pointer context it evaluates to const char*.
The solution is to declare
Buffer<const char*> s(20,"s.txt","rw");
template<class T>
class Buffer
{
unsigned int siz;
T *data;
public:
///constructor(size,filename,openmode)
Buffer(unsigned int s,const char* n, const char* m):siz(s)
{
data= new T[siz];
}
///destructor
~Buffer()
{
delete[] data;
}
///operator[]
T& operator[](unsigned int i)
{
if(i>siz-1)
{
unsigned int newsize=siz*2;
T* tmp=new T[newsize];
for(unsigned int j = 0; j < siz; j++)
{
tmp[j] = data[j];
}
siz=newsize;
delete[] data;
data=tmp;
}
return data[i];
}
};
int main() {
Buffer<char*> s(20,"s.txt","rw"); //20 long char*
for(unsigned int i=0;i<24;i++){ //it overwrites the size of s after default 20
s[i]="hey";
}
}
Live demo: http://ideone.com/Dgdcui
You're attempting to store a string literal in a char* variable - indicating that it is writable.
A string literal will typically be stored in the read only data segment of your application binary (See this question)
From the C++ FAQ
...it turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which therefore cannot necessarily be modified
Attempting to write to a memory location in the read-only data segment will cause your program to terminate - hence the crash.
Related
I'm attempting to implement an intvector in C++ and am getting a "Segmentation fault: 11" error. I understand this has something to do with memory management, and considering how new I am to C++ it could definitely be a pretty minor mistake. I debugged the code with valgrind and was given messages such as the following:
Use of uninitialized value of size 8, Invalid read of size 4,Conditional jump or move depends on uninitialized value(s).
My best guess is it has something to do with how I'm implementing the arrays. I originally had the arrays stored on the heap but changed it to the stack and still got the same error. I've already implemented an intvector in java, so I was attempting to use similar logic here, which perhaps is part of the issue.
#include <iostream>
#include "IntVector.h"
#include <cmath>
using namespace std;
int num_elements = 0;
int array_size = 0;
int expansion_factor;
void IntVector::expandArray(){
int tempArr[array_size*2];
for(int i =0;i<array_size;i++){
tempArr[i] = array[i];
}
array = tempArr;
array_size = array_size * 2;
}
void IntVector::add(int val){
int tempArr[array_size];
if(array_size == num_elements){
expandArray();
array[num_elements] = val;
}
else{
for(int i = 0;i<array_size;i++){
tempArr[i] = array[i];
}
tempArr[num_elements] = val;
array = tempArr;
}
num_elements++;
}
void IntVector::remove(int index){
}
int IntVector::get(int index) const{
return index;
}
void IntVector::removeLast(){
}
void IntVector::set(int index, int val){
}
std::string IntVector::toString()const {
return "";
}
IntVector::IntVector(int initial_size){
int* array = new int[initial_size];
}
IntVector:: ~IntVector(){
delete[] array;
}
int main(){
IntVector v(0);
v.add(5);
}
#ifndef INTVECTOR_H_
#define INTVECTOR_H_
using std::cout;
class IntVector {
private:
int* array;
int num_elements;
int array_size;
int expansion_factor;
void expandArray();
public:
void add(int val);
void remove(int index);
int get(int index) const;
void removeLast();
void set(int index, int val);
std::string toString() const;
IntVector(int initial_size);
~IntVector();
};
#endif
As mention in the comments, there are definitely some holes in your understanding of C++. Really when dealing with header files you should have a main.cpp, someotherfile.h, someotherfile.cpp. That just best practices to avoid redefinition errors.
There was quite a bit wrong with the way you accessed the private variable. If a class has a private( or even public) variable you don't have to redeclare it each time you want to change its value.
There were one or two major flaws with the way you expanded the vector. If the vector size is initialized to 0 then 0*2 is still 0 so you never actually increased the size. Secondly, when you set the original array = to the new array the new array was just a local array. This means that the memory wasn't actually allocated permanently, once the function ended the temparr was destroyed.
I know this was probably a lot but if you have any question feel free to ask.
main.cpp
#include "IntVector.h"
int main()
{
IntVector v;
IntVector x(10);
v.push(5);
v.push(5);
v.push(5);
v.push(5);
v.push(5);
v.print();
cout << endl;
x.push(5);
x.push(5);
x.push(5);
x.push(5);
x.push(5);
x.print();
return 0;
}
IntVector.h
#include <string>
#include <iostream>
using namespace std;
class IntVector {
private:
int *array;
int num_elements;
int array_size;
//int expansion_factor =; you would only need this if you plan on more than double the vector size
void expandArray(); //normally c++ array double in size each time they expand
public:
//Constructors
IntVector(); //this is a contructor for if nothing is called
IntVector(int initial_size);
//setters
void push(int val); //add
void pop(); //removelast
void remove(int index); //remove
void at(int index, int val); //set
//Getters
int at(int index);
//std::string toString(); I'm changing this to print
void print(); //will print the contents to the terminal
//Deconstructor
~IntVector();
};
IntVector.cpp
#include "IntVector.h"
//constructors
IntVector::IntVector() //no arguments given
{
array = new int[0];
num_elements = 0;
array_size = 0;
}
IntVector::IntVector(int initial_size)
{
array = new int[initial_size];
num_elements = 0;
array_size = initial_size;
}
void IntVector::expandArray()
{
int *tempArr;
if(array_size == 0){
array_size = 1;
tempArr = new int[1];
} else {
//make sure to allocate new memory
//you were creating a local array which was destroy after the function was completed
//using new will allow the array to exist outside the function
tempArr = new int[array_size * 2];
}
for (int i = 0; i < array_size; i++)
{
tempArr[i] = array[i];
}
//make sure to delete the old array otherwise there is a memory leak.
//c++ doesn't have a garbage collector
delete[] array;
array = tempArr;
array_size = array_size * 2;
}
void IntVector::push(int val)
{
num_elements++;
//checking if vector needs to increase
if (array_size <= num_elements)
{
expandArray();
array[num_elements-1] = val;
}
else
{
array[num_elements-1] = val;
}
}
void IntVector::remove(int index)
{
//not sure how to implment this becuase each element has to be a number.
}
int IntVector::at(int index)
{
return array[index];
}
void IntVector::pop()
{
num_elements = num_elements-1; //not really removing it from the "vector" but it won't print out again
}
void IntVector::at(int index, int val)
{
array[index] = val;
}
void IntVector::print()
{
for (int i = 0 ; i < num_elements; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
IntVector::~IntVector()
{
delete[] array;
}
output
5 5 5 5 5
5 5 5 5 5
Hopefully, the comments help. I changed the name of the functions to better match the actual vecter class the already exists in C++. I think it's good to pick apart already defined functions like this because you get a better understanding of how they actually work and not just how to use them.
If you got any questions just leave a comment
I have to create a copy constructor for my object, which look like this;
class DTable {
private:
std::string s_name;
int* *array;
int size;
public:
DTable();
DTable(std::string sName);
DTable(DTable &pcOther);
~DTable();
void vSetName(std::string sName);
std::string info();
int getValue(int index, bool &ok);
bool setValue(int index, int val);
const int defaultArrSize = 10;
const std::string defaultArrName = "Default Name";
};
Where array variable points at array of int*. Copy constructor i came up with looks like this;
DTable::DTable(DTable & pcOther) {
s_name = pcOther.s_name + "_copy";
size = pcOther.size;
array = new int*[size];
for (int i = 0; i < size; i++) {
array[i] = new int;
*array[i] = pcOther.*array[i];
}
}
The problem is that, i just cannot copy values of pointed int array to another array. Solution like this leaves me with error
expression must have pointer to member type
Also,
array[i] = pcOther.array[i];
is wrong, because that just copies references, so after altering one object, copy of it will be altered too. I want to avoid that.
I'd love to use different structure for this, but it has to be dynamically allocated array of int*
You can use the memcpy(),
void * memcpy ( void * destination, const void * source, size_t num );
or
*array[i] = *(pcOther.array[i])
for e.g.
DTable::DTable(DTable & pcOther) {
s_name = pcOther.s_name + "_copy";
size = pcOther.size;
array = new int*[size];
for (int i = 0; i < size; i++) {
array[i] = new int;
*array[i] = *(pcOther.array[i]);
// or
memcpy ( array[i], pcOther.array[i] , sizeof(int)*1 );
}
}
While I was trying to create an array in c++ class, there arose a problem while using the constructor. Here is the code:
int stacksize = 100;
int* buffer;
int stackpointer[3]= {-1, -1, -1};
public:
threestack(int stacksize_u)
{
int buffer_u[stacksize_u*3];
this->buffer = buffer_u;
this->stacksize = stacksize_u;
}
threestack()
{
int buffer_u[(this->stacksize)*3];
this->buffer = buffer_u;
}
This actually did not work. When I create the array in the declaration, however, it worked:
int stacksize = 100;
int buffer[300];
int stackpointer[3]= {-1, -1, -1};
Can anybody tell me what is wrong while I was using the constructor?
PSS: Here is the whole class and test program:
class threestack
{
int stacksize = 100;
int* buffer;
int stackpointer[3]= {-1, -1, -1};
public:
threestack(int stacksize_u)
{
int buffer_u[stacksize_u*3];
this->buffer = buffer_u;
this->stacksize = stacksize_u;
}
threestack()
{
int buffer_u[(this->stacksize)*3];
this->buffer = buffer_u;
}
bool push(int stacknum, int value);
bool pop(int stacknum);
int peek(int stacknum);
bool empty(int stacknum);
};
bool threestack::push(int stacknum, int value)
{
if(stackpointer[stacknum-1]+1 >= stacksize)
{
cout<<"Plz do not try to push to a full stack"<<endl;
// printf("stackpointer = %d\n", stackpointer[stacknum-1]);
return 0;
}
else
{
stackpointer[stacknum-1]++;
buffer[stackpointer[stacknum-1]+(stacknum-1)*stacksize] = value;
return 1;
}
}
int threestack::peek(int stacknum)
{
if(stackpointer[stacknum-1] < 0)
{
printf("No element in stack now.\n");
return 0;
}
else
{
printf("stackpointer = %d\n", stackpointer[stacknum-1]);
return buffer[stackpointer[stacknum-1]+(stacknum-1)*stacksize];
}
}
bool threestack::pop(int stacknum)
{
if(stackpointer[stacknum-1] < 0)
{
printf("Plz do not try to pop an empty stack.\n");
return 0;
}
else
{
stackpointer[stacknum-1]--;
}
return 1;
}
bool threestack::empty(int stacknum)
{
if(stackpointer[stacknum-1] < 0)
{
return true;
}
else
{
return false;
}
}
int main(int argc, const char * argv[])
{
threestack test;
test.push(1,5);
// test.pop(1);
// test.pop(1);
int i;
for(i=0; i<101; i++)
{
test.push(2, i);
printf("%d\n", test.peek(2));
}
cout<<endl;
printf("The top of stack 1 is %d\n", test.peek(1));
// std::cout << "Hello, World!\n";
return 0;
}
C++ arrays have a fixed size at compile time.
This is why your test module works - the size (=300) is known at compile time.
That's mandatory because the size of an array is in fact part of it's type, implying that
the type of int[1] is very different from int[2].
Yet it is not known when you kind of "dynamically" create the array in the constructor.
The way out is allocating dynamic memory using the new and delete [] operators.
Even better, try to use shared_ptr, unique_ptr or auto_ptr.
This
int* buffer;
is not a declaration of an array. It is a declaration of a pointer to int.
In constructor
threestack(int stacksize_u)
{
int buffer_u[stacksize_u*3];
this->buffer = buffer_u;
this->stacksize = stacksize_u;
}
all these two statements
int buffer_u[stacksize_u*3];
this->buffer = buffer_u;
are invalid. Firest of all sizes of arrays shall be constant expressions. Secondly you assign adrress of the first element of a local array to pointer buffer. After exiting from the constructor this address will be invalid because the local array will be destroyed.
You should either allocate dynamically array using operator new and assigning its value to data member buffer or use container std::vector instead of the dynamically allocated array.
I'm using an example code given to me by another C++ coder for a project. I'm a new student of C++ language and I wondered is there a possible memory leak / bugs in this class file given to me (PlacementHead.cpp):
#include "PlacementHead.h"
#include <string>
#include <iostream>
#include <string.h>
PlacementHead::PlacementHead(int width, int height, int gap, char* s) {
width_ = width;
height_ = height;
gap_ = gap;
size_ = (width*height)+1;
set_ = new char[size_ + 1];
from_ = new int[size_ + 1];
original_ = new char[size_ + 1];
strcpy(set_,s);
strcpy(original_,s);
}
PlacementHead::~PlacementHead() {
}
int PlacementHead::getSize() { return size_; }
int PlacementHead::getHeight() { return height_; }
int PlacementHead::getWidth() { return width_; }
int PlacementHead::getGap() { return gap_; }
// Palauttaa indeksissä i olevan suuttimen
char PlacementHead::getNozzle(int i) {
return set_[i-1];
}
// Asettaa indeksissä i olevan suuttimen
void PlacementHead::setNozzle(int i, char c) {
set_[i-1] = c;
}
// Merkitsee suuttimen poimituksi poistamalla sen listasta
void PlacementHead::markNozzle(int i, int bankPos) {
set_[i-1] = ' ';
from_[i-1] = bankPos;
}
// Palauttaa seuraavan poimimattoman suuttimen indeksin
int PlacementHead::getNextUnmarkedPos() {
for (int i=0; i<size_; i++) {
if (set_[i]!=' ') {
return i+1;
}
}
return 0;
}
// Palauttaa suuttimen alkuperäisen sijainnin pankissa
int PlacementHead::getBankPos(int i) {
return from_[i-1];
}
// Plauttaa alkuperäisen ladontapaan suutinjärjestyksen
void PlacementHead::reset() {
//for (int i=0; i<size_; i++) {
// set_[i] = original_[i];
//}
strcpy(set_,original_);
}
// Tulostusmetodi
void PlacementHead::print() {
std::cout << "ladontapaa:\n";
for (int h=height_; h>0; h--) {
for (int w=width_; w>0; w--) {
int i = ((h-1)*width_)+w;
std::cout << getNozzle(i);
}
std::cout << "\n";
}
}
PlacementHead.h:
#ifndef PLACEMENTHEAD_H
#define PLACEMENTHEAD_H
class PlacementHead {
public:
PlacementHead(int size, int rows, int gap, char* s);
~PlacementHead();
int getSize();
int getHeight();
int getWidth();
int getGap();
char getNozzle(int i);
void setNozzle(int i, char c);
void markNozzle(int i, int bankPos);
int getNextUnmarkedPos();
int getBankPos(int i);
void reset();
void print();
private:
char* set_;
int* from_;
char* original_;
int size_;
int width_;
int height_;
int gap_;
};
#endif
I notice that there is dynamic allocation of memory, but I don't see a delete anywhere...is this a problem? How could I fix this if it is a problem?
Thnx for any help!
P.S.
I noticed there is no keyword class used in this example?...Can you define a class like this?
It's impossible to say without seeing the class definition (the
header); if size_, etc. are something like
boost::shared_array, or std::unique_ptr, there is no leak.
If they are simply int*, there is a leak.
Of course, no C++ programmer would write this sort of code
anyway. The class would contain std::vector<int> and
std::string. Judging from what we see here, the author
doesn't know C++.
the code has leak . the constructor allocates the memory .Destructor or some other function have to clean that before the object gets destroyed
Another problem is that your code does not obey Rule of three (links here and here)
once you will write code like:
{
PlacementHead a(0,0,0,"asdsa");
PlacementHead b(0,0,0,"asdsa");
a = b; // line 1
} // here segfault
you will get segfault, in line 1, pointers will be copied from b to a, and once you will finally have destructors, pointers will be deleted twice, which is wrong. This is called shallow copy, you need deep copy, where new array will be allocated.
I am trying to create custom array indexed from 1 using subscript operator. Getting value works fine, but I have no clue, why assign using subscript operator doesn't work.
class CEntry {
public:
CKey key;
CValue val;
CEntry(const CKey& key, const CValue& val) {
this->key = key;
this->val = val;
}
CEntry& operator= (const CEntry& b) {
*this = b;
return *this;
};
};
...
class EntriesArray {
public:
CEntry **entries;
int length;
EntriesArray(int length) {
this->length = length;
entries = new CEntry*[length];
int i;
for (i = 0; i < length + 1; i++) {
entries[i] = NULL;
}
};
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return *entries[index - 1];
};
};
Constructs array this way
EntriesArray a(5);
This works
a.entries[0] = new CEntry(CKey(1), CValue(1));
cout << a[1].val.value << endl;
This doesn't work
a[1] = new CEntry(CKey(1), CValue(1));
EDIT:
Using
CEntry *operator=( CEntry *orig)
it compiles okey, but gdb stops at
No memory available to program now: unsafe to call malloc warning: Unable to restore previously selected frame
with backtrace
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff5f3ffff8
0x00000001000013c8 in CEntry::operator= (this=0x0, orig=0x1001008d0) at /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp:20
20 /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp: No such file or directory.
in /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp
At first... This:
CEntry& operator= (const CEntry& b) {
*this = b;
return *this;
};
Shouldn't work (this should result in recursive call of operator=).
The second thing is that you're trying to assign CEntry * to CEntry, this would work if you had CEntry *operator=( CEntry *orig), but I think this is bad coding practice.
This question may be related to this one.
I tried to fix your code; I believe that this is what you were trying to do:
(tested this code on g++ 5.3.0)
#include <iostream>
#include <stdexcept>
#include <string>
// Some implementation for CKey and CValue:
typedef int CKey;
struct CValue {
int value;
CValue(int value=0) : value(value) {}
};
class CEntry {
public:
CKey key;
CValue val;
CEntry(): key(0), val(0) {}
CEntry(const CKey& key, const CValue& val): key(key), val(val) {}
CEntry& operator= (const CEntry& b) {
this->key = b.key;
this->val = b.val;
return *this;
};
};
class EntriesArray {
public:
CEntry *entries;
int length;
EntriesArray(int length) {
this->length = length;
entries = new CEntry[length];
};
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw std::domain_error("out of bounds!");
}
return entries[index - 1];
};
};
int main(int argc, char* argv[]) {
using namespace std;
EntriesArray a(5);
// This works
a.entries[0] = CEntry(CKey(1), CValue(1));
cout << a[1].val.value << endl;
// This doesn't work
a[1] = CEntry(CKey(2), CValue(2));
cout << a[1].val.value << endl;
}
Also you might want to use a[1] as a[1].val.value e.g.:
cout << a[1] << endl;
To do this just add to this line to cEntry:
operator int() { return val.value; }
I hope it helps.
You could try replacing
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return *entries[index - 1];
};
with
void Add(const int index, CEntry *pEntry) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
entries[index - 1] = pEntry;
};
but since you are now storing references to objects allocated on the heap (with new) you will need a destructor ~EntriesArray() to delete them all.
Because EntriesArray::operator[] returns a CEntry &, but new CEntry returns a CEntry *.
Perhaps you want a[1] = CEntry(CKey(1), CValue(1))? (no new.)
By the way, your current definition of CEntry::operator= will lead to a stack overflow.
This
return *entries[index - 1];
dereferences a NULL pointer.
You want the pointer itself to be overwritten by a[1] = new CEntry(CKey(1), CValue(1));, not the pointed-to-value.
Try this:
class EntriesArray
{
public:
int length;
CEntry **entries;
EntriesArray( int length ) : length(length), entries(new CEntry*[length]())
{
}
// defaulted special member functions are inappropriate for this class
EntriesArray( const EntriesArray& ); // need custom copy-constructor
~EntriesArray(); // need custom destructor
EntriesArray& operator=(const EntriesArray&); // need custom assignment-operator
CEntry*& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return entries[index - 1];
}
};
Further to my comment above:
To make it work with writing new values, you probably need something like this
(I haven't double checked for off by one or ptr vs reference stuff)
CEntry& operator[] (const int index) {
if (index < 1) {
throw ArrayOutOfBounds();
}
// Add default elements between the current end of the list and the
// non existent entry we just selected.
//
for(int i = length; i < index; i++)
{
// BUG is here.
// We don't actually know how "entries" was allocated, so we can't
// assume we can just add to it.
// We'd need to try to resize entries before coming into this loop.
// (anyone remember realloc()? ;-)
entries[i] = new CEntry();
}
return *entries[index - 1];
};