Sid
Sid

Reputation: 73

C memory management in circular string array

I am pretty new to C, and trying to create a buffer which stores the last N lines of string input in a circular array. Relevant code:

char ** lines;
int last_line=0;
int max_lines=0;
int max_line_length=1000;

void main()
{
    ... //set max_lines dynamically, among other setup.
    int * len = malloc(sizeof(int));
    char s[max_line_length];
    lines=malloc(sizeof(char*) * max_lines);
    while(getLine(s, len) != EOF) {
        pushLine(s, *len);
    }
}

void pushLine(char * s, int len) 
{
    //Here is where I am trying to replace the previous string in the array
    char * t = realloc(lines[last_line], sizeof(char) * len);
    memcpy(t,s,len);
    lines[last_line++]=t;
    last_line = last_line % max_lines;
}

If I replace realloc() with malloc(), this works perfectly, but that would create a memory leak. When I use realloc(), it works fine for awhile, but then I notice that program locations seem to get randomly overwritten.

Any thoughts around what could be causing those errors?

Thanks!

Upvotes: 1

Views: 371

Answers (1)

Richard Chambers
Richard Chambers

Reputation: 17593

You need to do a malloc() before doing the realloc(). realloc() changes the already allocated memory. You should init the lines memory area to NULL first and then realloc() will perform a malloc() the first time since realloc() will operate like malloc() if the pointer is NULL.

See this writeup on realloc().

So add a line after the malloc() to initialize the area to null or use calloc() instead of malloc().

See this writeup on calloc().

Upvotes: 1

Related Questions