Kotito Otitok
Kotito Otitok

Reputation: 1

Global variable is smashed

I have the next code:

#include <math.h>

int x;
float Temp = 0;

void main(){

x = 2;

for(;;){
   Temp=log(20);
}
}

I shortened my code to the important line. The problem I have is once x is declared as 2 and then I do log() function, this calculation alter to x variable and change it to a huge valour.

Codewarrior (the IDE I'm using to), says that Temp variable is in the location 0x0102 and x variable is in 0x0108.

I need x for a function in "MCUinit.h" so it's important that x variable isn't greater than 5, and codewarrior give like 5000 or even greater after doing log(whatever)

How could I do so that log() don't alter others variables?

thanks

Before doing log() function. https://ibb.co/6ZHh6D0

After doing log() function. https://ibb.co/Np99Sz4

Upvotes: -4

Views: 200

Answers (2)

Kotito Otitok
Kotito Otitok

Reputation: 1

Somehow I came up with a possible solution. I guess it isn't the best solution due to my programming level but it works.

As my program executed line Temp=log(20) its outcome was a bit mess because it was changing too many valours in the RAM with some kind of variables inside, and then log() was giving me its own valour and trash, smashing from its position 0x0100 and further. So what I did was to change 'float Temp' in ' float Temp[10] and I gathered the real valour and trash in that array. So I just had to take the interested valour.

Thanks for eveyone. I'm still here to heard new suggestion, anyway.

Upvotes: -2

Lundin
Lundin

Reputation: 213286

This is an obvious stack overflow. S08 is an incredibly resource-constrained 8 bit MCU. It is not a PC. It does not have a FPU. This means that you cannot and should not use floating point arithmetic, ever. Period. And avoid using 32 bit arithemtic in general.

What happens when you roll up math.h is that Codewarrior injects a bombastic software floating point lib, completely slaughtering all the available memory and CPU resources in the whole MCU, turning your program into a useless mess. One single log call was apparently enough to kill the stack. I'm not surprised, you have some 100-200 bytes of stack per default. And when that happens, the stack overflows into the .data/.bss memory areas where the variables x and Temp are stored, destroying it while writing gibberish in those areas.

If you actually need to use floating point calculations, then tough luck, you picked the wrong MCU. Should have picked a Cortex M4.

In addition, you should always place the stack so that it grows (it's a down-counting SP) into harmless memory areas, not into the .data/.bss sections. Why Codewarrior doesn't do this as default is very strange. Having the stack grow into the register map isn't ideal either, but in case you aren't using all the timer peripherals around 0x70 then it's at least a less bad scenario than corrupting all variables in the program.

Upvotes: 2

Related Questions