Memory questions

Hi,

Can someone help me with a general question about memory and how it might get corrupted?

If I have a simple data type (i.e. byte, int or long) and I try to put a value in it that's too big i.e. I attempt to store 260 in a byte, or 33,000 in a int. Then the value that actually get's stored in that variable will 'wrap around' but it won't corrupt any other memory - i.e. it won't overflow and corrupt the variable that happens to be stored in the adjoining bytes of memory? Or to put it another way, the value in the variable may be wrong, but at least no other nearby memory will be corrupted?

Secondly, if I start working with character arrays like this...
char test[8];
and then try to populate it with a string that's too long i.e.
strcpy(test,"helloworld");
Then because the word 'helloworld' is longer than the character array, the last two characters will overflow the array and corrupt the next two adjacent bytes of data? If the next two bytes aren't in use, then this won't cause problems, but if they are in use, then they will be corrupted?

Have I got it right so far? if I have, does this mean that if I've got a project that uses both simple data types and character arrays where some variables seem to be getting corrupted, I should be checking the code that manipulates the character arrays because that's the most likely cause of problems?

Thanks

I think you have the correct idea.

You should be careful to allocate enough space for your arrays and to ensure that you do not use an invalid index that writes beyond that allocated space.

Dynamic memory management does not work well in the limited SRAM available in an Arduino.

...R

Then the value that actually get's stored in that variable will 'wrap around' but it won't corrupt any other memory - i.e. it won't overflow and corrupt the variable that happens to be stored in the adjoining bytes of memory?

Correct.

If the next two bytes aren't in use,

You may not be using them directly as named variables, but depending on where they are (stack, heap, globals) the compiler may be using them.

If the next two bytes aren't in use, then this won't cause problems, but if they are in use, then they will be corrupted?

The next THREE bytes, in the example you cited (strcpy adds a terminating NULL, so the 10 characters need 11 elements in an array) will be stomped on. Whether that causes a problem, or not, remains to be seen.