When I access array elements through unique_ptr, a segfault occurs,Through vs debugging, I found that the type and data of std::unique_ptr<T[]> p is strange,I think it should be an array, but it looks like a string,No matter how many elements I push, the data of p points to "to", and other elements cannot be seen.
code
#include <memory>
#include <string>
#include <assert.h>
#include<vector>
#include<iostream>
#include <stack>
#include <string>
#include <sstream>
template <typename T>
class FixedCapacityStockOfStrings {
public:
FixedCapacityStockOfStrings(const int cap) {
p = std::make_unique<T[]>(cap);
MAX = cap;
}
bool isEmpty() {
return N == 0;
}
size_t const size() { return N; }
void push(T& item){
//assert(N < MAX - 1);
if (N == MAX-1) resize(2 * MAX);
p[N++] = item;
}
T pop() {
assert(N > 0);
T item = p[--N];
p[N] = nullptr;//Segmentation fault is here
if ( N <= MAX / 4) resize(MAX / 2);
return item;
}
size_t max() const { return MAX; }
void clear() {
N = 0;
}
private:
void resize(int max) {
auto t = std::make_unique<T[]>(max);
for (int i = 0; i < N; i++) {
t[i] = p[i];
}
p.reset();
p = std::move(t);
MAX = max;
}
std::unique_ptr<T[]> p;
size_t N,MAX;
};
int main() {
FixedCapacityStockOfStrings<std::string> s(100);
std::string line,item;
while (std::getline(std::cin, line)) {
std::istringstream items(line);
while (items >> item) {
if (item != "-")
s.push(item);
else if (!s.isEmpty()) std::cout << s.pop() << " ";
}
std::cout << "(" << s.size() << " left on stack)" << " max stack : " << s.max() << std::endl;
s.clear();
}
}
Note that p[N]
has type std::string&
for T
= std::string
, so what
p[N] = nullptr;
does is call std::string::operator=(const char*)
with parameter nullptr
. This is not a parameter you're allowed to pass to this assignment operator; it expects a 0-terminated string.
Edit: Improved based on suggestion by @Remy Lebeau
You should go with
p[N] = T{};
instead.
You forgot to initialize N
in the constructor, so it is a garbage value and reading it is undefined behavior.
p
contains an array of std::string. When you assign p[N] = nullptr
, you assign a C string to std::string. C string is a pointer to a null-terminated character array and nullptr is not a valid C string.
In the statement p[N] = nullptr;
, you are assigning a nullptr
to a std::string
, which is Undefined Behavior .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.