I am a Java programmer trying out c++, and I am not used to manual memory management.
I wrote a piece of code which attempts to generate a sierpiński triangle, and it was roughly ported from Java to C++. The Java code works but its C++ equivalent does not:
#include <vector>
#include <string>
using namespace std;
int main() {
long unsigned int n;
cin >> n;
std::vector<string> arr(1);
arr.at(0) = "\\";
for(long unsigned int i = 0; i < n; i++){
int size = arr.size();
arr.resize(size*2);
for(int ii = 0; ii < size; ii++){
string t = "";
t.append(arr.at(ii));
for(long unsigned int i2 = 0; i2 < size-sizeof(t); i2++){
t.append(" ");
}
t.append(arr.at(ii));
arr.at(size+ii) = t;
}
}
for(long unsigned int i = 0; i < arr.size(); i++){
cout << arr.at(i) << endl;
}
return 0;
}
I know the issue has something to do with vectors, but it could also have something to do with memory management as the program would start to consume a lot of memory and never exit.