Hi, I'm on excersise 5-6 in The C Programming Language book and while making the itoa function program encountered a seg fault...
Code:
/* itoa.c */
/* second version of itoa
* this time using pointers
* instead of array indexing
*/
/* includes */
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
/* function prototypes */
int batoi(char *s);
char *bitoa(int n);
void reverse(char *s);
int bstrlen(char *s);
int main(int argc, char **argv)
{
if (argc != 2) { /* print usage and exit */
fprintf(stderr, "Usage: %s <num>\n", argv[0]);
return EXIT_FAILURE;
}
char *string = argv[1];
printf("\n\nConverting string to integer...\n\n");
sleep(5);
int integer = batoi(string);
printf("Just to clarify here is the number (+1 to prove its a number): %d\n", integer + 1);
sleep(5);
printf("\n\nConverting back to string format...\n\n");
sleep(5);
string = bitoa(integer);
printf("And here's the resulting string: %s\n", string);
return EXIT_SUCCESS;
}
int batoi(char *s)
{
int num, sign;
sign = (*s == '-') ? -1 : 1;
for (num = 0; *s != '\0'; s++) /* get number */
num = 10 * num + (*s - '0');
return num * sign;
}
char *bitoa(int n)
{
int sign = n;
char *buffer, *ptr; /* used for the resulting string */
ptr = buffer;
if (n < 0)
n = -n; /* make positive for manipulation */
do {
*buffer = n % 10 + '0'; /* get digit */
++buffer;
} while (n /= 10);
if (sign < 0) { /* if original number was negative then add the '-' symbol to the string */
*buffer = '-';
++buffer;
}
*buffer = '\0';
reverse(buffer);
return ptr;
}
void reverse(char *s)
{
int temp;
int count_s, count_t;
char *t = s;
for (*t += bstrlen(s), count_s = 0, count_t = bstrlen(s); count_s < count_t; ++s, ++count_s, --t, --count_t) { /* reverse the string, swapping each char on opposite sides until s and t meet halfway */
temp = *s;
*s = *t;
*t = temp;
}
}
int bstrlen(char *s)
{
int num = 0;
while (*s) { /* count chars */
++num;
++s;
}
return num;
}
I'm sure its the bitoa function and I've tried allsorts to solve the problem.
I got rid of the seg fault by just returning a pointer to a normal string like this...
Code:
char *bitoa(int n)
{
char buffer[] = "hello world";
char *ptr = buffer;
return ptr;
}
but that results in printing random binary chars, I don't know what else to try??