program works even when hexfile size is greater than flash memory [duplicate]

I am working with AT89S51 microcontroller and using keil to write program in C. It produced a hex file of size about 4875 bytes but flash memory on the microcontroller is only 4kbytes.

I programmed the flash successfully and the program is also working fine.

I am glad its working but I want to know why is it working since there is no enough space on flash to program my code on the microcontroller.

Let me know if you need any additional info.

• Learn to read the HEX file : it contains the addresses at which each line of code is loaded. Check these addresses are within the flash memory area... – Brian Drummond May 29 '16 at 10:12
• tnks @BrianDrummond I should have done that. But what if the program size(not the hex file) is actually bigger than 4kB, will the program still load on the flash i.e., only upto 4kb?? Maybe the programming software will warn and not allow to program the microC?? – Jasser May 29 '16 at 10:22
• Then something (probably the linker) should warn you. If not, get better software tools. – Brian Drummond May 29 '16 at 10:24

2 Answers

The hex file contains more than the bytes of the program - it also contains "control" information.

I assume that it looks something like this:

:02000000052ECB
:10000800F000030E83120313A0000A08A1008A015E


Which means that you probably have the "Intel HEX file format". You can find a lot of references on the net.

Some indications:

• The ":" indicates the start of the new line and already indicates it is not a pure hex file (so that mistakes can be avoided).
• The first byte (first 2 digits) indicates the kind of line of data it is. When the line starts with ":10", an address is provided.
• At the end of the line there is a checksum.
• ... - You can easily "google" for the Intel Hex format

This explains why your hex file is bigger - the extra data avoids mistakes. The format also allows smaller files than the memory you are filling and the data does not need to be contigious.

• As well as control data, each actual byte of data is two characters in the hex file - so even without any control data the hex file would be twice the size of the data. – Tom Carpenter May 29 '16 at 17:46

I don't know this type of controller, but it is possible that only the first 4 kB are loaded on the memory, and not the last bytes of your program. You should give it a full test using all possible inputs, it might stop working properly at some point.