When I pass an array into a function in a dynamic library with the signature:
void itoa(int n, char s[]);
and calling it from my main function:
int main(int argc, char *argv[])
{
if (argc > 1) {
char *arg = argv[1];
printf("%s\n", arg);
}
char str[15]={'0', '0', '0', '0', '0',
'0', '0', '0', '0', '0',
'0', '0', '0', '0', '\0'};
itoa(INT_MIN, str);
printf("%s\n", str);
return 1;
}
Walking through the code with gdb I can see that the program is crashing on the following line:
s[i++] = n % 10 + '0';
Note that i's initial value is declared 0 at the top of the function.
Why is it crashing?
UPDATE
Note that it works locally.
#include <stdio.h>
#include <limits.h>
#include "c_lib.h"
void itoa_local(int n, char s[])
{
int min_int = 0;
int i, sign = 0;;
if (INT_MIN == n) {
min_int = 10;
n++;
}
if ((sign = n) < 0) n = -n;
do {
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
if (sign < 0) s[i++] = '-';
s[i] = '\0';
if (min_int == 10) s[0]++;
reverse(s);
}
int main(int argc, char *argv[])
{
if (argc > 1) {
char *arg = argv[1];
printf("%s\n", arg);
}
char str[15]={'0', '0', '0', '0', '0',
'0', '0', '0', '0', '0',
'0', '0', '0', '0', '\0'};
itoa_local(INT_MIN, str);
printf("%s\n", str);
return 1;
}
The answer is in the initial post. I answered my own question so I did not have to delete it. Archival reasons mainly.