"AddressSanitizer: stack-use-after-scope" when trying to access element of vector of pointers

  address-sanitizer, c++

Why the following code

#include <iostream>
#include <vector>

typedef struct Number {
    int number = 15;
} Number;

int main() {
    std::vector<Number*> nums(5);
    for (size_t i = 0; i < nums.size(); ++i) {
        Number num;
        nums[i] = &num;
    }

    std::cout << nums[1]->number << "n";

    return 0;
}

trigger "AddressSanitizer: stack-use-after-scope", but when i comment line 15: std::cout << nums[5]->number << "n"; it compiles well? How to fix it?

Compile command: clang++ main.cpp -fsanitize=address,undefined -fno-sanitize-recover=all -std=c++17 -O2 -Wall -Werror -Wsign-compare -g -o debug_solution && ./debug_solution

Source: Windows Questions C++

LEAVE A COMMENT