AnsweredAssumed Answered

Hard fault when using std::string substr() in this situation

Question asked by mafull on Jul 27, 2017
Latest reply on Jul 27, 2017 by AvaTar

Hey guys,

 

I have a function that parses messages of my own format and splits them into an opcode and (0-3) operands.

With 0 or 1 operand, it works fine; on the second operand, the msg.substr(start, (pos - start)); causes a hard fault every time without fail on my STM32F4. Stepping into substr() in the debugger it appears to occur inside the constructor for basic_string. I tested the code in an online compiler and it works fine, so I'm guessing it's some kind of memory allocation issue. Just doesn't make sense to me that it works for the first operand and not the second. Any ideas guys?

 

You'll also notice some commented out use of std::vector. This is another issue with STM32 C++ development in Keil I believe which I could also do with help sorting - currently any call to push_back kills the program (possibly a similar issue to above?).

 

 

#include <iostream>
#include <string>
#include <stdexcept>


void ParseMessage(const std::string msg)
{
   std::string opCode;
   //std::vector<std::string> operands;
   std::string operands[3];
   uint8_t operandCount = 0;

   opCode = msg.substr(1, 3);
   std::cout << "Opcode: " << opCode << std::endl;

   if(msg[4] == '#') {
      // We have at least one operand
      size_t pos;
      size_t start = 5;

      pos = msg.find('#', start);
      while(pos != std::string::npos) {
         operands[operandCount++] = msg.substr(start, (pos - start));
         std::cout << "Operand " << operandCount << ": " << operands[operandCount-1] << std::endl;
         // Store middle operands
         //operands.push_back(msg.substr(start, pos - 1));
         start = pos + 1;
         pos = msg.find('#', start);
      }

      // Store the final operand
      //operands.push_back(msg.substr(start, msg.length() - 2));
      //uint16_t tmp = msg.length();
      operands[operandCount++] = msg.substr(start, ((msg.length() - 1) - start));
      std::cout << "Operand " << operandCount << ": " << operands[operandCount-1] << std::endl;
   }

}

int main()
{
     ParseMessage("<SSG#0.7#0.3#0.05>");
   return 0;
}

Outcomes