When I run the following C code I get the values:
- 222222222
- 312222222
- 102222222
I was expecting the values:
- 222222222
- 31
- 10
Why does the char number[] defined in my intToStr function remember previous values? I thought once the function call ended all local data was more or less destroyed.
#include <stdio.h>
void intToStr(int n);
int main(void)
{
intToStr(222222222);
intToStr(31);
intToStr(10);
return 0;
}
void intToStr(int n)
{
char number[10];
int l = 0;
if (n < 0)
{
l ;
number[0] = '-';
n *= -1;
}
int nCopy = n;
while (nCopy > 9)
{
nCopy /= 10;
l ;
}
int r;
while (n > 9)
{
r = n % 10;
n /= 10;
number[l--] = r '0';
}
number[l] = n '0';
printf("%s\n", number);
}
CodePudding user response:
the array should not remember the old data
For each program, the C standard either:
- specifies what the program should do
- says that it is not specified what the program should do
It hardly ever says that the program should not do something in particular.
In this case, the standard says that it is not specified what characters should be in the array at the start of the function. They can be anything at all. Characters from the previous call is one particular case of "anything at all".
CodePudding user response:
That's undefined behavior. If only the first 3 character are set, it may print 312222222
or it may print 312???????????????????
The last characters in char number[10]
are not initialized, that means the compiler may decide to leave it alone and the old values stay, or something else happens.
Otherwise printf
doesn't know where the string end, it keeps printing until it randomly hits a zero.
If there is buffer overrun printf
finds a different set of characters in memory (which we are not supposed to be accessing) and the program keeps printing those same characters until it randomly hits a zero and finally stops.
To fix it, simply make sure there is '\0'
at the end. You can also add additional check to make sure the length does not exceed the buffer size
Working example:
char number[10];
int l = 0;
if (n < 0)
{
l ;
number[0] = '-';
n *= -1;
}
if (n < 0) return;
int nCopy = n;
while (nCopy > 9)
{
nCopy /= 10;
l ;
}
int len = l;
if (len 1 > sizeof(number))
return;
number[len 1] = '\0';
int r;
while (n > 9)
{
r = n % 10;
n /= 10;
number[l--] = r '0';
}
number[l] = n '0';
printf("%s\n", number);