Can someone help me figure out what's wrong with this program? (C) -
i doing easy challenge on /r/dailyprogrammer in c. managed write on hundred lines of code, , spend couple hours total on (usually end chickening out), , figure out compiler errors. now, when run it, segfault. i'm doing wrong?
yes, it's sort of homework help, @ least tried before coming here.
#include <ctype.h> #include <stdio.h> #include <string.h> #define maxlen 50 #define limit 20 #define true 1 #define false 0 char* reverse(char *a); char* ltoa(long i); long atol(char *a); /* note: handle leading zeros. */ long palindromize(long p); int ispalindrome(long p); /* meat. */ int main(int argc, char *argv[]) { long p; int count, limr; p = (long) argv[1]; count = 0; limr = false; while (true) { p = palindromize(p); count++; if (ispalindrome(p)) { break; } else if (count == limit) { limr = true; break; } } if (limr) { printf("it might palindrome, it'd take quite while find out.\nlast number reached: %ld\n", p); } else { printf("palindrome found! after %d steps, we've found %ld.\n", count, p); } } long palindromize(long p) { return (atol(reverse(ltoa(p)))) + p; } int ispalindrome(long p) { char *t, *r; t = ltoa(p); r = reverse(ltoa(p)); if (t == r) { return true; } else { return false; } } /* utility functions. */ /* converts string long integer. */ long atol(char *a) { int i, sign; long r; (i = 0; a[i] == '0'; i++) { i++; } if (a[0] == '-' || a[-1] == '-') { sign = -1; } else { sign = 1; } (; isdigit(a[i]); i++) { r = 10 * r + (a[i] - '0'); } return r * sign; } /* converts long integer string. , reverse based on ones in k&r. */ char* ltoa(long n) { char *a; int i, sign; if ((sign = n) < 0) { n = -n; } = 0; { a[i++] = n % 10 + '0'; } while ((n /= 10) > 0); if (sign < 0) { a[i++] = '-'; } a[i] = '\0'; return reverse(a); } char* reverse(char *s) { int i, j; char c; (i = 0, j = strlen(s)-1; i<j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } return s; }
in ltoa
declare char *a;
never malloc
space it. when access a[i]
crashes. problems this, remember simple first debugging step add print statements everywhere can @ least pinpoint error occurring.
looks ispalindrome
wrong too, not in seg fault way. i'll let figure out why =d
Comments
Post a Comment