Reputation: 1
the program that keeps accepting three numbers, and prints the maximum among the three. I am getting runtime error(SIGABRT) here's my code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char ch[30];
char *c[3];
long int i[3], mx_2;
int o;
while((fgets(ch,sizeof(ch),stdin))&&ch!='\0')
{
c[0] = (char *)malloc(10);
c[1] = (char *)malloc(10);
c[2] = (char *)malloc(10);
c[0] = strtok(ch," ");
c[1] = strtok(NULL," ");
c[2] = strtok(NULL," ");
i[0] = atoi(c[0]);
i[1] = atoi(c[1]);
i[2] = atoi(c[2]);
mx_2 = i[0] > i[1] ? (i[0] >i[2] ? i[0] : i[2]) : (i[1] > i[2] ? i[1] : i[2]);
printf("%ld\n",mx_2);
fflush(stdin);
for (o = 0; o < 3; o++) {
free(c[o]);
}
}
return 0;
}
any help guys thanks
Upvotes: 0
Views: 114
Reputation: 12668
When you do c[0] = malloc(10);
and some sentences later you do c[0] = strtok(...);
you are overwriting the pointer value at c[0]
with the result of strtok(3)
(which is itself a pointer), not copying the string contents. When you reach the for
loop of free(3)
you are passing to the free()
function the values given by strtok
and not the ones given from malloc()
(these were lost forever, when you reassigned the array c
values) so that's the most probable cause of your SIGABRT
.
By the way, you don't even need to do any of the malloc
's and free
's you do in your program. Just get a buffer long enough to store a whole line of input, and then use strtok to get all the chunks. On other side, you have to test the strtok
result, as if there's no more data (you input only two values) it will return NULL
.
This piece of code will do the work and not only for three values, but for any number up to the array size:
#include <stdio.h> /* for input output routines like fgets */
#include <stdlib.h> /* for the constant EXIT_SUCCESS */
#include <limits.h> /* for INT_MAX and INT_MIN */
#include <string.h> /* for strtok */
int main()
{
char buffer[1024];
while (fgets(buffer, sizeof buffer, stdin)) {
/* we have one full line of input up to sizeof buffer chars. */
int max = INT_MIN;
int min = INT_MAX;
char *s = strtok(buffer, " \t\n");
if (!s) {
fprintf(stderr, "Invalid line\n");
continue;
}
while (s) {
int x = atoi(s);
if (x > max) max = x;
if (x < min) min = x;
s = strtok(NULL, " \t\n");
}
if (max != INT_MIN)
printf("MAX: %d\n", max);
if (min != INT_MAX)
printf("MIN: %d\n", min);
} /* while */
return EXIT_SUCCESS;
} /* main */
Upvotes: 1
Reputation: 18420
Better use scanf for your task:
scanf(" %d %d %d", i, i+1, i+2);//note the leading space in the format
Upvotes: 0