cancel
Showing results for 
Search instead for 
Did you mean: 

[F767ZI, C++] A hard fault occurs during the initialization of an object

Hermis
Associate II

I am writing code for the NUCLEO-F767ZI board in C++.

Initially, I have three classes and their objects are defined as global variables in `usermain.cpp` in ${Project}\User\Src\:

SystemClass systemObj(1);
 
PwmClass servoObj(&htim3);
TLinkClass tlinkObj(&huart3);

SystemClass has the pointers of the PwmClass and TLinkClass objects as its members.

// systemlib.hpp
class SystemClass {
public:
  uint8_t ID;
  PwmClass* pPwm;
  TLinkClass* pTLink;
  ...
  SystemClass(uint8_t ID);
};
 
// baselib.cpp
SystemClass::SystemClass(uint8_t id) {
  ID = id;
}

The code works nicely as intended. Now, I want SystemClass to contain the PwmClass and TLinkClass objects as its member for simplicity. So the latter two objects are initialized by SystemClass.

// systemlib.hpp
class SystemClass {
public:
  uint8_t ID;
  PwmClass Pwm[SYS_PWM_NUM_TIMER];
  TLinkClass TLink;
 
  SystemClass(uint8_t ID);
};
 
// usermain.cpp
SystemClass systemObj(1);

It's a very simple change, but the code started to throw a hard fault just after the initialization of SystemClass.

0693W00000Y8y32QAB.png 

I've been struggling to figure out what causes the hard fault in vain. I am almost new to STM32 programming.

I tried to derive a simpler code that reproduces the same result but I failed on that, too. So I attached two STM32CubeIDE projects where one works and the other throws a hard fault. I think you can see the difference using the diff function provided by the IDE.

I want to know what caused the problem and how to avoid it. The solution will be a very important breakthrough for my future projects. Thank you.

3 REPLIES 3
KnarfB
Principal III

Debug-step deeply into your code and find the line where the fault occurs.

From what I saw:

If you make PwmClass Pwm[SYS_PWM_NUM_TIMER]; a member, the PwmClass constructor is called which calls HAL macros for timers. But, since LinkTimer has not been called for that fresh object, htim is uninitialized. The C++ RAII idiom comes to my mind...

hth

KnarfB

Thank you for the valuable answer!!

By the way, isn't RAII concerned about the destruction of an object?

Apart from debugging the issue, what do you think is the best practice for embedded systems?: between having objects as members and carrying the pointer for them. The latter is cumbersome for me due to the tedious initialization of individual objects to be pointed to and a bunch of member access operators. The former method is simple and easy to maintain, but STM32 seems to not like it.

Hermis
Associate II

I don't know why, but when I made all the members from the base class defined by the initialization list, the HF stopped occurring. Now, I am going to use the init list whenever a class uses inheritance. TY.