I am trying to write a program to convert a hexadecimal number to a decimal, and then print the decimal value. The problem I am facing is that my for loop causes a segmentation fault.
printf("no segmentation fault so far..."); /*this printed*/
for (i=0; (c=getchar()) != '\n'; i++) {
printf("no segmentation fault after entering for loop"); /*this didn't print*/
I know this because as you can see from my code above all the code before the for loop were ran but the body wasn't executed. There could be a possibility that the for loop test case was not met and therefore it was skipped. To test for this, I put printf statements in other parts of my program as well. However, only the one above the for loop was executed. Here's my full code if it helps:
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#define MAXLEN 100
int htoi(char *s, int lim);
void copy(char *to, char *from);
int main(void) {
char *hexArray = (char *)malloc(MAXLEN);
htoi(hexArray, MAXLEN);
return 0;
}
int htoi(char s[], int lim) {
double decOutput;
int i = 0;
int c;
int size = MAXLEN;
printf("no segmentation fault so far...");
for (i=0; (c=getchar()) != '\n'; i++) {
printf("no segmentation fault after entering for loop");
if (isdigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
if(i >= size - 1) {
size = size + MAXLEN;
char *tmp = (char *)malloc(size);
copy(tmp, s);
free(s);
s = tmp;
printf("Buffer size increased to %d\n", size);
}
s[i] = c;
}
else {
printf("INVALID INPUT!!! Decimal output may be inaccurate.");
}
}
printf("exited loop");
for(i = 0; s[i] != '\0'; i++) {
printf("entered second for loop");
if (s[i] != '0' || (s[i+1] != 'x' && s[i+1] != 'X')) {
double y = pow(16, (double)i);
double x = s[i];
decOutput = decOutput + pow(x, y);
}
}
printf("%s", decOutput);
return decOutput;
}
void copy(char *to, char *from) {
int i = 0;
while((to[i] = from[i]) != '\0') {
i++;
}
}