Search code examples
c++iosxcodedynamic-arrays

Creating dynamically allocated arrays using Xcode's g++


So, I recently tried doing this:

void Foo(int **bar, int size) {
    bar = new int *[size];
    for (int i = 0; i < size; i++)
        bar[i] = new int[4];
    // Do other stuff
    return;
}

int main(int argc, char *argv[]) {
    int ** data;
    int size = atoi(argv[1]);
    Foo(data, size);
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < 4; j++)
            cout << "i = " << i << ", j = " << j << ", data = " << data[i][j] << endl;
        // Do other stuff
    }

    for (int i = 0; i < size; i++)
        delete[] data[i];
    delete[] data;
    return 0;
}

and invariably I would get a segfault right at that cout statement. After changing the code so that the array was dynamically allocated in main the problem went away. So, the difference between a segfault is whether or not an array is dynamically allocated and destroyed in the same function. This seems wrong to me as this shouldn't be a problem with traditional C++. I am using a MacBook with Xcode for the g++ command. Can anyone else confirm that Xcode's implementation does this?


Solution

  • It's nothing specific to Xcode or g++ - just a bug in your code - you need to pass bar by reference in order to use it as an output parameter.

    Change:

    void Foo(int **bar, int size)
    

    to:

    void Foo(int ** &bar, int size)
    

    Note that in general it's preferable to use e.g. std::vector rather than naked C-style pointers for arrays etc.