Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

realloc does not copy values correctly

I am trying to read a text file with unknown size into an array. I do that by reading one character at a time into the array and reallocate memory if the the end of the array is reached.

Starting from the increase in array size from 16 to 32, the realloc method copies only the first 4 characters.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main()
{
    int *text_arr = malloc(1*sizeof(int));
    text_arr[0] = '\0';
    int text_len=1;
    int i=0;
    FILE *fp;

    fp = fopen("1.txt", "r");
    
    while ((text_arr[i] = fgetc(fp)) != EOF) {
        /* increment i for next loop */
        i++;

        /* extend the array if needed */
        if (i >= text_len) {
            /* debug prints */
            printf("Text: ");
            for (int n=0; n<i; n++)
                printf("%c,", text_arr[n]);
            printf("\n\n");
            
            /* double array size */
            text_len *= 2;
            text_arr = (int*)realloc(text_arr, text_len);
        }
    }
    text_arr[i] = '\0';

    fclose(fp);
    
    return 0;
}

What could be the problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are working with sizeof (int) sized objects, you need to make sure to multiply your requested number of bytes by this size when you reallocate.

realloc(text_arr, sizeof (int) * text_len);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading