Hello all,
I'm trying to work through two separate but likely related problems:
1) When I try to use the class constructor below by setting the value of 'size'; the 'size' variable value is not maintained within the int location stored in the class. This is shown in the output I've copied below.
2) When I try to access the member function getVal(...) I get a segmentation fault.
I've boiled down my code to a subset that still shows this behavior.
It has been quite some time since I've programmed in c/c++ and I've been trying to find where I could be going wrong here; for quite a while. Any advice to solve the issues above, or to explain why I'm getting this type of behavior, would be extremely appreciated.
My system is:
> uname -a
Linux debian-richard 2.6.22.6 #1 SMP Thu Sep 6 21:18:12 EDT 2007 i686 GNU/Linux
My compiler is:
> g++ -v
Using built-in specs.
Target: i486-linux-gnu
Configured with: ../src/configure -v --enable-languages=c,c++,fortran,objc,obj-c++,treelang --prefix=/usr --enable-shared --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --enable-nls --with-gxx-include-dir=/usr/include/c++/4.1.3 --program-suffix=-4.1 --enable-__cxa_atexit --enable-clocale=gnu --enable-libstdcxx-debug --enable-mpfr --enable-checking=release i486-linux-gnu
Thread model: posix
gcc version 4.1.3 20070812 (prerelease) (Debian 4.1.2-15)
thanks,
Richard
-----------------------------------
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
class data_matrix {
private:
int size;
int *a;
data_matrix(int size, int val, bool random);
public:
data_matrix(int size);
data_matrix(int size, int val);
~data_matrix();
int getVal(int row, int col);
int setVal(int row, int col, int val);
int getSize();
};
data_matrix::data_matrix(int inpSize)
{data_matrix(inpSize, 0, true);}
data_matrix::data_matrix(int inpSize, int val)
{data_matrix(inpSize, val, false);}
data_matrix::data_matrix(int inpSize, int val, bool random) {
size = inpSize;
printf("the input size=%d\nafter the update the size is now = %d\n",inpSize,size);
a = new int[size*size];
if (random) {
srand(time(NULL));
for (int i=0; i<size; i++)
a[i] = rand();
} else {
for (int i=0; i<size; i++)
a[i] = val;
}
}
data_matrix::~data_matrix() {
delete[] a;
a = NULL;
}
int data_matrix::getVal(int row, int col) {
return a[row*size + col];
}
int data_matrix::setVal(int row, int col, int val) {
a[row*size + col] = val;
return 0;
}
int data_matrix::getSize() {
printf("the size variable is: %d\n",size);
return size;
}
int main() {
data_matrix b(100), c(200,2);
printf("Starting tests\n");
printf("b(100) size=%d\n",b.getSize());
printf("c(200,2) size=%d\nc[1,1]=%d",c.getSize(),c.getVal(1,1));
}
-----------------------
Has this output:
-----------------------
./tester.exe
the input size=100
after the update the size is now = 100
the input size=200
after the update the size is now = 200
Starting tests
the size variable is: -1080196504
b(100) size=-1080196504
Segmentation fault