I was making a C program to convert 12 hour clock into 24 hour clock with the format of input being HH:MM:SSAM or HH:MM:SSPM and 24hr clock output being HH:MM:SS
#include <stdio.h>
#include <stdlib.h>
int main(){
char *time = malloc(11 * sizeof(char));
scanf("%11s", time);
if (time[8] == 'A' || time[8] == 'P')
{
if (time[8] == 'A')
{
time = realloc(time, (9 * sizeof(char)));
printf("%s\n", time);
}
else
{
time = realloc(time, (8 * sizeof(char)));
char str[3];
sprintf(str, "%c%c", time[0], time[1]);
int hours;
hours = atoi(str);
int milhours;
milhours = hours + 12;
char milstr[3];
sprintf(milstr, "%d", milhours);
time[0] = milstr[0];
time[1] = milstr[1];
printf("%s\n", time);
}
}
else
{
printf("give a standard format\n");
return 0;
}
return 0;
}
There is no compilation error,but the program doesnt run because of buffer overflow. When I reduce the size of dnamic array time , is it necessary that the last 2 elements of time will be removed?
EDIT: I updated time, str and milstr for NULL terminator and the buffer overflow problem is resolved. Thanks for the recommended reading!
free(time)after realloc?sizeof(char)equals 1 by definition.timeis a commonly used identifier, better use your own.