0

As the title says, I got a problem with the same value assigned by two different constructors to two unrelated variables in my program.

This is the first part:

template<typename N>
    N* readMany( const json::Value& jsonSource, std::size_t size ) {
        N* result = new N[size];
        
        //check code
        std::cout << "result: " << result << std::endl;
        std::cout << std::flush;
        
        for( size_t i = 0; i < size; i++ ) {
            auto number = jsonSource.get( i, false );
            result[i] = static_cast<N>( number.asFloat() );
        }
        
        return result;
    }

And this is the second part:

Value::Value() {
        element = new JsonNull();
        //check code
        std::cout << "Constructor call: " << element << std::endl;
        std::cout << std::flush; 
    }

And this is what is printed to stdout:

Constructor call: 0x55dd64bfddb0
Constructor call: 0x55dd64c23040
Constructor call: 0x55dd64c23060
Constructor call: 0x55dd64c23080
Constructor call: 0x55dd64c23040
Constructor call: 0x55dd64c23060
Constructor call: 0x55dd64c23080
result: 0x55dd64c23060 <-- HERE
Constructor call: 0x55dd64c23080
Constructor call: 0x55dd64c23060 <-- AND HERE
Constructor call: 0x55dd64c23040

As you can see in two parts of my code the variables got the same values. And because these values are deleted in two other parts of my code in destructors, I'm getting SEGFAULT for double freeing of my memory.

I's using a debugger and then the above print code and got the same results. I don't know what may be the issue. I can't even post any sample code for You to test, because I can't isolate the problem in a sample. The above findings are all what I got.

EDIT:

These are destructors:

Value::~Value() {
        delete element;
    }
NumberArray::~NumberArray() {
    delete[] array;
}
Felix.leg
  • 622
  • 1
  • 4
  • 13
  • 3
    I don't see any destructors code. Please post a [mre]. In any case, you can avoid bugs by using `std::vector` instead of raw C arrays, smart pointers instead of raw ones, and avoiding manual `new`/`delete`. – wohlstad Mar 29 '23 at 11:10
  • Which implementation of JSON are you using? – SebastianWilke Mar 29 '23 at 11:17
  • Possibly you violated the [Rule of Three](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three)? It's *highly* unlikely that your compiler would have borked `new` implementation such that it would return same pointer without `delete` in between. But wohlstad suggestion is the best - don't use raw `new` and `delete` in C++. It's just asking for trouble. – Yksisarvinen Mar 29 '23 at 11:18
  • OK, I got rid of the problem. I still don't know what caused it, but a change to `std::vector` solved it. – Felix.leg Mar 29 '23 at 11:25
  • the issue seems to be in code you did not show. Please always try to create a [mcve] – 463035818_is_not_an_ai Mar 29 '23 at 12:25

0 Answers0