My class has a member std::string received;, initialized at an empty string in its constructor, along with a function printReceived that prints the string to cout.
In main(), an instance of the above class is created, and printReceived is called.
Instead of getting an empty string, I get totally unexpected values (but always the same):
-
If
printReceivedisstd::cout<<"Received ":<<received<<std::endl;, I getReceived: eived:as output. -
A string constant present in a function of another class which is not called, if this file is linked.
Where could that come from ? It’s getting me mad… All variables are correctly initialized. I’ve never had this problem before, and I’ve programmed a lot in C++.
Here is a complete minimal example as asked:
CellularTest.cpp
#include "A.h"
#include <iostream>
int main()
{
A s;
s.println("AT+CSQ");
return 0;
}
A.cpp
#include "A.h"
A::A()
: received("")
{
}
void A::println(char* s)
{
received+=s+'\n';
treatReceived();
}
void A::treatReceived()
{
std::cout<<"Received: "<<received<<std::endl;
}
A.h
#include <iostream>
#include <string>
class A
{
public:
A();
void println(char* s);
private:
std::string received;
void treatReceived();
};
Makefile
CellularTest: CellularTest.o CellularTest.cpp A.o
g++ CellularTest.o A.o -o CellularTest
CellularTest.o: CellularTest.cpp
A.o: A.cpp A.h
clean:
rm *.o
rm CellularTest
The output I get is:
Received: eived:
operator+=has lower precedence thanoperator+. So inprintln, you’re doing this:Which is like
Which is incrementing the pointer
sby 10 bytes and then appending the string pointed to by the resultingchar*toreceived, and the string literalRecieved:is happening to be stored just after the string literalAT+CSQ. So memory might look likeAT+CSQ\0Received: \0and incrementingAT+CSQby 10 is actually theeinReceived:. So there you have it.Change that to
Or alternatively