C++ Compiler Initializer Issue?

I’ve been using the DS18B20 library and had real flakiness. Sometimes the temperature was way too high. I finally tracked it down today after a few hours and it seems to be a value not initializing. I can’t figure out how this could be happening. My code is the library DS18B20 and OneWire. Here’s the relevant issue:

Here’s the DS18B20 constructor:

DS18B20::DS18B20(uint16_t pin, bool singleDrop) : _singleDrop(singleDrop){
ds = new OneWire(pin);
}

Here’s how I use it:

_Sensor = new DS18B20(_Pin, true);

And here’s my test code

DS18B20::DS18B20(uint16_t pin, bool singleDrop) : _singleDrop(singleDrop){
ds = new OneWire(pin);
Serial.println("Byte value2: " + String(type_s));
}

This prints: “Byte value2: 15” to the serial port.

DS18B20::DS18B20(uint16_t pin, bool singleDrop) : _singleDrop(singleDrop), type_s(0) {
ds = new OneWire(pin);
Serial.println("Byte value2: " + String(type_s));
}

This prints: “Byte value2: 0” to the serial port.

Can anyone explain what’s going on here? Is there any created assembly code I can look at to diagnose this or is there a way to set a breakpoint when something writes to this address? The type_s byte variable is just a member of the DS18B20 object and should be initialized to 0.

Or, am I just dumb and missing something obvious?

Thanks,
Mark

So, you are trying to modify the library in the IDE?

Since the dynamic object will just be created on the heap its fields won’t be initialised unless done explicitly in code.
But the “random” value after instantiation shouldn’t matter when you perform a sensor search (DS18B20::search()) to set the correct type.

On the other hand, if you already know your type, adding a way to set the type from outside, may be a good addition.

PRs welcome :+1:

Update:
I just looked at the most recent version (0.1.6) and in that I had removed the type_s field completely as it’s redundant anyway - the sensor ID (addr[]) provides all relevant data.

1 Like

Wow, it’s been too long since I programmed in C++.

Thanks,
Mark