I'm pretty new to C, and I'm trying to write a function that takes a user input RAM size in B, kB, mB, or gB, and determines the address length. My test program is as follows:
int bitLength(char input[6]) {
char nums[4];
char letters[2];
for(int i = 0; i < (strlen(input)-1); i++){
if(isdigit(input[i])){
memmove(&nums[i], &input[i], 1);
} else {
//memmove(&letters[i], &input[i], 1);
}
}
int numsInt = atoi(nums);
int numExponent = log10(numsInt)/log10(2);
printf("%s\n", nums);
printf("%s\n", letters);
printf("%d", numExponent);
return numExponent;
}
This works correctly as it is, but only because I have that one line commented out. When I try to alter the 'letters' character array with that line, it changes the 'nums' character array to '5m2'
My string input is '512mB' I need the letters to be able to tell if the user input is in B, kB, mB, or gB. I am confused as to why the commented out line alters the 'nums' array.
Thank you.
In your input
512mB
,"mB"
is not digit and is supposed to handled in commented code. When handling those characters,i
is 3 and 4. But because length ofletters
is only 2, when you executememmove(&letters[i], &input[i], 1);
,letters[i]
access out of bounds of array so it does undefined behaviour - in this case, writing to memory ofnums
array.To fix it, you have to keep unique index for
letters
. Or better, for bothnums
andletters
sincei
is index ofinput
.