Bharath
Bharath

Reputation: 169

triggers an exception while using malloc

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;
}

Upvotes: 0

Views: 362

Answers (1)

Mahonri Moriancumer
Mahonri Moriancumer

Reputation: 6003

The most critical issue (as pointed out n.m and Michael Walz) is re-sizing of inp:

    inp = (char *)realloc(inp,sizeof(char)*(i));

First of all, when i is zero, zero is passed to realloc() as the new size. The documented behavior for realloc(inp, 0); is equivalent to free(inp);. This means that any additional access of the (now freed) memory pointed to by inp is likely to cause problems; including segmentation faults, etc. Such as the following line:

     inp[j + 1] = '\0'; 

The above line is a bad thing if inp == NULL.

Here is a replacement for the realloc() line:

{
...
char   *tmp;
size_t  inpLen=strlen(*inp);

tmp = realloc(*inp, (inpLen * 2) + 1);
if(NULL == tmp)
   /* handle the error. */
inp=tmp;
...
}

See my complete version of the question code here.

Upvotes: 1

Related Questions