EmbLogic's Blog

error in realloc

The following code (a part of mdc project for creating master array) shows run time error for code length of more than 4 bits i.e realloc is working fine for 16 times but not more than 16 times.

char ch, *ma;

ch = fgetc(fp_test);
*ma = ch;

for(k = 1; (ch = fgetc(fp_test)) != EOF;)
{
for(j = 0; j < k; j++)
{
if (ch == ma[j])
break;
}

if (j == k)
{
t = realloc(ma, sizeof(char));
ma = t;
t = NULL;
*(ma + k) = ch;
k++;
}
}

2 Responses to error in realloc

  1. Ganesh Kale says:

    use a temporary variable to strore the count of allocated memory.
    initialize temp to how much memory allocated during maloc.

    temp = temp+1;
    ma = realloc(ma, temp);

    Good Luck………

  2. shiv says:

    First of all, if you are using a charactre pointer :

    char ch, *ma;

    ch = fgetc(fp_test);
    *ma = ch;

    Here you need to allocate memory of char size to ma.

    Second thing, the above mention line for fgetc is not required before the for loop, because, it’s being called twice before going into the ‘for’ statement body execution.
    for(k = 1; (ch = fgetc(fp_test)) != EOF;)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>