0

I try to use a 2D array of shared_ptr. If I fill it manually all works as expected. But if I use two for loops instead it crashes with an SIGSEV on position 0/0.

I tried boost and std shared_ptr, without any difference.

#include <stdio.h>
#include <memory>

using namespace std;

int main(){
    int x = 3;
    int y = 3;

    shared_ptr<shared_ptr<string>> bar = shared_ptr<shared_ptr<string>>(new shared_ptr<string>[x]);
    for(int i=0; i<x; i++)
        bar.get()[i] = shared_ptr<string>(new string[y]);

    //Crashes: SIGSEGV on 0/0
//  for(int i=0; i<x; i++)
//      for(int j=0; j<y; j++)
//              bar.get()[i].get()[j] = "x";


    //works
//  for(int i=0; i<x; i++){
//      bar.get()[i].get()[i] = "0";
//      bar.get()[i].get()[i] = "1";
//      bar.get()[i].get()[i] = "2";
//  }

    //works
//  for(int i=0; i<x; i++){
//      bar.get()[i].get()[0] = "0";
//      bar.get()[i].get()[1] = "1";
//      bar.get()[i].get()[2] = "2";
//  }

    //works
//  for(int i=0; i<x; i++){
//      bar.get()[0].get()[i] = "0";
//      bar.get()[1].get()[i] = "1";
//      bar.get()[2].get()[i] = "2";
//  }

    //works
    bar.get()[0].get()[0] = "00";
    bar.get()[0].get()[1] = "01";
    bar.get()[0].get()[2] = "02";
    bar.get()[1].get()[0] = "10";
    bar.get()[1].get()[1] = "11";
    bar.get()[1].get()[2] = "12";
    bar.get()[2].get()[0] = "20";
    bar.get()[2].get()[1] = "21";
    bar.get()[2].get()[2] = "22";

    for(int i=0; i<3; i++){
        for(int j=0; j<3; j++)
            printf("%s ", bar.get()[i].get()[j].c_str());
        printf("\n");
    }

    return 0;
}
Verim
  • 1,065
  • 9
  • 17
  • 1
    That's not a 2D array. It's a single pointer to a single pointer to a single string. Your crashing code is invoking undefined behavior, and your working code is invoking undefined behavior. – Drew Dormann Aug 12 '15 at 20:43
  • An array is the same as an pointer, isn't it? How should the line correct look? – Verim Aug 12 '15 at 21:11
  • An array is **a collection of things**. A pointer is **the location of a thing**. Whoever told you they were the same was trying to fool you. Try `std::string bar[3][3];` – Drew Dormann Aug 12 '15 at 21:18

0 Answers0