Start New Discussion within our Software Development Community

Hello friends,
I am trying to work on a project that dynamically allocates memory when needed for a string array. I just keep getting memory faults when reallocating memory but can't find any thourough tutorials on realloc besides the man page. So basically, I malloc 201 character spaces in an array and put the first 200 chars of file line, if the file does not contain a newline character I want to keep reallocing memory until it does but can't seem to find the right combonation of realloc and strcat etc. If anyone could help me it would be greatly apprieciated.

while( (!feof(file)) && lineCount < 11999 ) {            //will loop til end of file
        lines[index] = malloc(201*sizeof(char));        //give 201 spaces for the pointer at index
        fgets(lines[index], 200, file);                 //gets first 200 chars
        temp = strchr(lines[index], '\n');              //check for new line character
    while(temp == NULL){                                //while loop, while the newline char is not found,                                                                   keep fgetting 200chars of the file until it is
    //printf("%s", lines[index]);                        //For testing
        lines[index] = realloc(lines[index],200)        //add 200 more spaces and
        fgets(tempString,200,file);                    //temp dont want to override
        strcat(lines[index],tempString);                //cat temp string onto new string.
        temp = strch(lines[index], '\n');

    }//index's iterated below

Figured it out!

For anyone wondering, you have to increment on top of the size already allocated, so store your size as a variable int size, and make sure you increment that instead of just reallocating the address to a set number.

realloc(string, size+sizeAdding);

This question has already been answered. Start a new discussion instead.