PaperCode46
PaperCode46

Reputation: 21

Proper way to realloc in c

I have the following bit of code:

FILE *fp;
fp = fopen("input_file","r");
size_t newsize = 1;
char buffer[MAX_SIZE];
char *text;
text = malloc(sizeof(char) * newsize);
strcpy(text,"");

while (fgets(buffer,sizeof(buffer),fp) != NULL)
{
    newsize += strlen(buffer)
    text = realloc(text,newsize);
    strcat(text,buffer);
}

At the very end of my program, I free(text). Do I need to free after every realloc? Right now my program "works" but when I run it through valgrind I get many errors.

Edit: I edited out all my other code, this is the error I get even before the realloc part

==3953== Warning: client switching stacks?  SP change: 0x7ff0004c0 --> 0x7fe85f190
==3953==          to suppress, use: --max-stackframe=8000304 or greater
==3953== Invalid write of size 4
==3953==    at 0x40076E: main (p21.c:37)
==3953==  Address 0x7fe85f19c is on thread 1's stack
==3953==
==3953== Invalid write of size 8
==3953==    at 0x400774: main (p21.c:37)
==3953==  Address 0x7fe85f190 is on thread 1's stack
==3953==
==3953== Invalid write of size 8
==3953==    at 0x400793: main (p21.c:43)
==3953==  Address 0x7fe85f188 is on thread 1's stack
==3953==
==3953== Invalid read of size 8
==3953==    at 0x4E8C38D: __fopen_maybe_mmap (iofopen.c:60)
==3953==    by 0x400797: main (p21.c:43)
==3953==  Address 0x7fe85f188 is on thread 1's stack
==3953==
==3953== Warning: client switching stacks?  SP change: 0x7fe85f190 --> 0x7ff0004c0
==3953==          to suppress, use: --max-stackframe=8000304 or greater

Upvotes: 1

Views: 111

Answers (1)

Do I need to free after every realloc?

No. realloc frees the old memory block and gives you a new memory block to play with.

Unless it can expand the memory block without freeing it, in which case it does that and gives you the same block back. But also in this case, since nothing extra was allocated there's nothing extra to free.

Upvotes: 2

Related Questions