Search code examples
c++pointersdynamic-memory-allocation

Seg Fault - Passing variable to method changes global value


I'm a newbie to c++ and am trying to do some basic object creation using dynamic memory. I'm passing an int argument to a method and it is changing the value of the global variable. I think it has something to do with the way I'm allocating memory for new objects, I cant get it to compile any other way.

int main () {
    int inp;
    CRectangle rectb (2,2);
    cout << "enter number of items to add" << endl;
    cin >> inp; // let's say inp = 7
    rectb.addItemsArray(inp);
    cout << "inp after adding items: " << inp << endl; // inp is now 1.
}

header files:

class CRectangle {
    int width;
    int height;
    item *items[]; // SOLUTION: change this line to "item *items"
    int input;

public:
        CRectangle (int,int);
        int addItemsArray(int);
        int area () { return (width*height); }
        int get_items(int);

};

-and-

class item {
    int foo;
    char bar;
public:
    //SOLUTION add "item ();" here (a default constructor declaration without arguments)
    item (int, char);
    int get_foo();
    char get_bar();
};

method:

int CRectangle::addItemsArray(int in) {
    cout << "value of in at begginning:" << in << endl; //in = 7
    int i;
    i = 0;
    //SOLUTION: add "items = new item[in];" on this line.
    while (i < in) {
        items[i] = new item(1, 'z'); //SOLUTION: change this line to "items[i] = item(1, 'z');"
        i++;
    }
    cout << "value of in at end " << in << endl; //in = 7
    return 1;
}

Sometimes I get a bus error or seg fault. Sometimes it works as expected with lower numbers like 2 or 3, but not always.

Any help would be greatly appreciated.

Edit (CRectangle's constructor):

CRectangle::CRectangle (int a, int b) {
    width = a;
    height = b;
} 

(item's constructor):

/* SOLUTION add default item constuctor
item::item() {
    foo = 0;
    bar = 'a';
}
*/

item::item(int arg, char arg2) {
    foo = arg;
    bar = arg2;
}

Solution

  • It looks like you forgot to create the items array...

    You defined a dynamic allocated array (not item *items[100], but item *items[]). Before you can use the array, you have to allocate memory to hold the items:

    items = new item[100];
    

    and dont forget to delete it with

    delete [] items; 
    

    at the end. ;)

    And instead of

    int i;
    i = 0;
    while (i < in) {
       items[i] = new item(1, 'z');
       i++;
    }
    

    i would use

    for (int i=0; i<in; i++)
    {
       items[i] = new item(1, 'z');
    }