Reputation: 249
If I create a two class members of char*
type and is array. And if I resize first member of the class it overwrite the second member with same values.
Why it happens?
Is it some memory management issues?
#include <iostream>
using namespace std;
class myclass
{
private:
const char *arr1[0];
const char *arr2[4] {
"one",
"two",
"three",
"four"
};
public:
void run() {
int f = 0;
*this->arr1 = new char[4];
for(f = 0; f < 4; f++) {
this->arr1[f] = "foo";
}
for(f = 0; f < 4; f++) {
cout << this->arr2[f] << endl;
}
}
};
int main()
{
myclass *my = new myclass();
my->run();
return 0;
}
Output
foo
foo
foo
foo
Upvotes: 0
Views: 75
Reputation: 22152
const char *arr1[0];
Zero-sized arrays are not allowed in standard C++. Your compiler is allowing it as an extension to the language.
Even if your compiler has this extension, dereferencing an array of size 0
causes undefined behavior and you are doing this here:
*this->arr1 = new char[4];
I don't know what your intention here is, either you want
const char *arr1[4];
in which case *this->arr1 = new char[4];
is unnecessary or you want
const char **arr1;
in which case it should be this->arr1 = new const char*[4];
.
You should not use char*
to manage strings, use std::string
instead, which does the memory management for you. Similarly, for multiple strings use std::vector<std::string>
instead of char**
.
There doesn't seem any reason to use dynamic memory allocation in main
either. The same way as you should use std::vector
to manage dynamically-sized arrays of objects instead of using new[]
/delete[]
, don't use dynamic memory allocation to create single objects if you don't have a good reason for it and if you have to, use std::unique_ptr
instead of raw new
/delete
.
int main()
{
myclass my;
my.run();
return 0;
}
This does the same without dynamic allocation.
Upvotes: 4