I am trying for a program which adds spaces between two characters in a string,my programs works for the first testcase but triggers an exception for the next one,please help me
#include<stdio.h>
#include<conio.h>
#include "stdlib.h"
#include "ctype.h"
#include "string.h"
struct test {
char input[20];
char output[20];
} testDB[12] = { { "A B C", "A B C" },
{ " abc ", "a b c" },
{ "A b C", "A b C" },
{ "123", "1 2 3" },
{ "", "" },
{ " a1B2c", "a 1 B 2 c" },
{ "a b c", "a b c" },
{ "!@#$", "! @ # $" },
{ "A!@b", "A ! @ b" },
{ " ", "" },
};
void remove_space(char *inp)
{
int i = 0, ch, j = 0, k = 0;
while (inp[i])
{
ch = inp[i];
if (ch == ' ')
{
j = i + 1;
while (inp[j] == (' '))
{
j++;
}
inp[k] = inp[j];
k++;
i = j + 1;
}
else
{
inp[k] = inp[i];
k++;
i++;
}
}
inp[k] = '\0';
return;
}
void add_space(char *inp)
{
int i = 0, j;
while (inp[i])
{
i++;
}
inp = (char *)realloc(inp,sizeof(char)*(i));
j = 2 *( i - 1);
inp[j + 1] = '\0';
while (i>0 && j>0)
{
i--;
inp[j] = inp[i];
j--;
inp[j] = ' ';
j--;
}
return;
}
void testCases()
{
int i;
char * inp[10];
for (i = 0; i < 10; i++)
{
inp[i] = (char *)malloc(sizeof(char)*(strlen(testDB[i].input)+1));
strcpy(inp[i], testDB[i].input);
remove_space(inp[i]);
add_space(inp[i]);
if (strcmp(inp[i], testDB[i].output) == 0)
printf("PASSED\n");
else
printf("FAILED\n");
}
return;
}
int main()
{
testCases();
getch();
return 0;
}
mallocthrow the exception?inp = (char *)realloc(inp,sizeof(char)*(i));You are reallocating to exactly the same size you already have. You need twice that, and another one for'\0'.