Program crashes

this code compile but it crashes right after. Can someone tell me what is wrong?

#include <cstdlib>
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{

class tablica{

int *t;
int rozmiar;

public:

tablica(int il_elem)
{
rozmiar=il_elem;
}
~tablica(void){cout<<rozmiar;}
void wstaw(int pozycja, int wartosc)
{

t[pozycja]=wartosc;

}
int tablica::pobierz(int pozycja)
{

cout<<t[pozycja]<<endl;
}

};

tablica eee(4);
eee.wstaw(2,3);

system("PAUSE");
return EXIT_SUCCESS;
}
Last edited on
It doesn't compile, with error:

01.cpp:26: error: extra qualification ‘main(int, char**)::tablica::’ on member ‘pobierz’

Changing that line to

int pobierz(int pozycja)

fixes that and it compiles.

On running, it segFaults. This means you are trying to use memory that is not yours.

Running it under a debugger reveals the following line to be at fault:

t[pozycja]=wartosc;

(gdb) print pozycja
$1 = 2

pozycja is found to equal 2.

Upon examinig the code, t is found to be an int pointer that you have never set. It is pointing at some random memory, so when you try to write to it, you are writing over some random memory. This is bad. The operating system stops the program. To fix this, you must make that pointer point at some memory that actually is yours.
Last edited on
thank very you much, but could u tell me how to do it? I'm a total a noob and my knowledge = "thinking in c++"
in tablica constructor, add:
 
t = new int;


If you need a whole array of int's, add brackets and the array size you need to the code above. new int[SIZE]
Last edited on
You need to understand what a pointer is and what an int is, and how a pointer to an int is not the same thing as an int. If you don't understand the difference, you will make this mistake over and over again in different forms.
Topic archived. No new replies allowed.