简体   繁体   English

在C中重新分配的正确方法

[英]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) . 在程序的最后,我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. 现在我的程序可以运行,但是当我通过valgrind运行它时,会遇到很多错误。

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

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. 否。重新realloc释放了旧的内存块,并为您提供了一个新的内存块供您使用。

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. 但在这种情况下,由于也没有分配任何额外的东西,因此没有多余的东西可供释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM