<code>#include <memory>
#include <iostream>
#define BLOCKSIZE 100000
struct MyClass {
std::shared_ptr<char[]> block;
MyClass() :
block(std::make_shared<char[]>(BLOCKSIZE)) {}
void fill_block() {
for(size_t i=0; i<BLOCKSIZE; ++i) {
block[i] = static_cast<char>(i % 99);
}
}
void print_one(size_t i) {
if (i < BLOCKSIZE) {
std::cout << static_cast<int>(block[i]);
} else {
std::cout << "Index out of range!";
}
}
};
int main() {
for(size_t i=0; i<1000; ++i) {
MyClass x;
x.fill_block();
x.print_one(i);
}
return 0;
}
</code>
<code>#include <memory>
#include <iostream>
#define BLOCKSIZE 100000
struct MyClass {
std::shared_ptr<char[]> block;
MyClass() :
block(std::make_shared<char[]>(BLOCKSIZE)) {}
void fill_block() {
for(size_t i=0; i<BLOCKSIZE; ++i) {
block[i] = static_cast<char>(i % 99);
}
}
void print_one(size_t i) {
if (i < BLOCKSIZE) {
std::cout << static_cast<int>(block[i]);
} else {
std::cout << "Index out of range!";
}
}
};
int main() {
for(size_t i=0; i<1000; ++i) {
MyClass x;
x.fill_block();
x.print_one(i);
}
return 0;
}
</code>
#include <memory>
#include <iostream>
#define BLOCKSIZE 100000
struct MyClass {
std::shared_ptr<char[]> block;
MyClass() :
block(std::make_shared<char[]>(BLOCKSIZE)) {}
void fill_block() {
for(size_t i=0; i<BLOCKSIZE; ++i) {
block[i] = static_cast<char>(i % 99);
}
}
void print_one(size_t i) {
if (i < BLOCKSIZE) {
std::cout << static_cast<int>(block[i]);
} else {
std::cout << "Index out of range!";
}
}
};
int main() {
for(size_t i=0; i<1000; ++i) {
MyClass x;
x.fill_block();
x.print_one(i);
}
return 0;
}
<code>g++ shared_ptr_test.cpp -o shared_ptr_test
./shared_ptr_test
Segmentation fault
</code>
<code>g++ shared_ptr_test.cpp -o shared_ptr_test
./shared_ptr_test
Segmentation fault
</code>
g++ shared_ptr_test.cpp -o shared_ptr_test
./shared_ptr_test
Segmentation fault
Is it because block should not be initialized with std::make_shared<char[]>(BLOCKSIZE)
?
If I use a unique_ptr
there’s no issue.