View previous topic :: View next topic |
Author |
Message |
jseidmann
Joined: 04 Nov 2004 Posts: 67
|
Strings in function act as if they are STATIC, but are not! |
Posted: Fri Jul 27, 2007 11:57 am |
|
|
Hello,
I have a function in my code that does some work with strings, and I declare two strings in the function (s[4 and sTemp[8]). For some reason, I declare these two normally:
Code: |
char s[4];
char sTemp1[8];
|
The problem is that I would assume that whenever i go into these functions, that they should be all full of null values whenever I start the function, but when I enter this function the second time, they still have the same value as before, so I have to clear them! Is this how its supposed to be? It doesnt make sense to me. I dont declare them as static variables! |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Fri Jul 27, 2007 12:10 pm |
|
|
If local variables in a function are not declared as 'static', the RAM used
by them is released by the compiler, upon exiting from that function. The
RAM can then be used for local variables in other functions or in main().
There is no requirement for the compiler to set the value of the released
RAM bytes to zero. All local variables (that are not static) must be
initialized by you, with lines of code, upon entry into the function.
This behavior is part of the C language. |
|
|
jseidmann
Joined: 04 Nov 2004 Posts: 67
|
|
Posted: Fri Jul 27, 2007 12:12 pm |
|
|
Is there an easy way to initialize them? Is there a function built in to do so? |
|
|
Douglas Kennedy
Joined: 07 Sep 2003 Posts: 755 Location: Florida
|
|
Posted: Fri Jul 27, 2007 12:24 pm |
|
|
Read the manual maybe #ZERO_RAM is for you or
char s[5]={'t','e','s','t'}; |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Fri Jul 27, 2007 12:30 pm |
|
|
Here are some ways to do it. The one that uses the least amount of
ASM code is the first method, shown below (at least for small arrays):
Code: | void my_func(void)
{
int8 i;
char s[4];
char sTemp1[8];
s[0] = 0;
s[1] = 0;
s[2] = 0;
s[3] = 0;
for(i = 0; i < sizeof(s); i++)
s[i] = 0;
memset(s, 0, sizeof(s));
} |
|
|
|
Pret
Joined: 18 Jul 2006 Posts: 92 Location: Iasi, Romania
|
|
Posted: Mon Jul 30, 2007 5:43 am |
|
|
If you are working with string functions, is enough to use s[0] = 0; or char s[4] = ""; |
|
|
|