user-0 提问: 如何避免realloc申请空间过大

回复:
user: user-1
content: 检查是否资源泄漏的办法之一： 在任务管理器 进程 查看 选择列 里面选择：内存使用、虚拟内存大小、句柄数、线程数、USER对象、GDI对象 让你的程序(进程)不退出,循环执行主流程很多遍，越多越好，比如1000000次甚至无限循环，记录以上各数值，再隔至少一小时，越长越好，比如一个月，再记录以上各数值。如果以上两组数值的差较大或随时间流逝不断增加，则铁定有对应资源的资源泄漏！  仅供参考//输出PROG中有但LIST中没有的文本行，即集合PROG-LIST #include <stdio.h> #include <string.h> #include <stdlib.h> #include <search.h> #define MAXCHARS 512 int MAXLINES=10000,MAXLINES2; char *buf,*buf2; char PROG[256]="PROG";//程序Program需要的文件列表 char LIST[256]="LIST";//dir /b /s生成的实际文件列表List FILE *fp,*fl; int i,c,n,L,hh; int ignore_case=0; char ln[MAXCHARS]; int icompare(const void *arg1,const void *arg2) {    return stricmp((char *)arg1,(char *)arg2); } int compare(const void *arg1,const void *arg2) {    return strcmp((char *)arg1,(char *)arg2); } int main(int argc,char **argv) {     if (argc>1) strcpy(PROG,argv[1]);//命令行参数1覆盖PROG     if (argc>2) strcpy(LIST,argv[2]);//命令行参数2覆盖LIST     if (argc>3) ignore_case=1;//若存在命令行参数3，忽略大小写     if ((fl=fopen(LIST,"rt"))==NULL) {         fprintf(stderr,"Can not open %s\n",LIST);         fprintf(stderr,"Usage: %s [PROG] [LIST] [-i]\n",argv[0]);         return 1;     }     if ((fp=fopen(PROG,"rt"))==NULL) {         fclose(fl);         fprintf(stderr,"Can not open %s\n",PROG);         fprintf(stderr,"Usage: %s [PROG] [LIST] [-i]\n",argv[0]);         return 2;     }     buf=(char *)malloc(MAXLINES*MAXCHARS);     if (NULL==buf) {         fclose(fl);         fclose(fp);         fprintf(stderr,"Can not malloc(%d LINES*%d CHARS)!\n",MAXLINES,MAXCHARS);         return 4;     }     n=0;     hh=0;     i=0;     while (1) {         if (fgets(ln,MAXCHARS,fl)==NULL) break;//         hh++;         L=strlen(ln)-1;         if ('\n'!=ln[L]) {//超长行忽略后面内容             fprintf(stderr,"%s Line %d too long(>%d),spilth ignored.\n",LIST,hh,MAXCHARS);             while (1) {                 c=fgetc(fl);                 if ('\n'==c || EOF==c) break;//             }         }         while (1) {//去掉行尾的'\n'和空格             if ('\n'==ln[L] || ' '==ln[L]) {                 ln[L]=0;                 L--;                 if (L<0) break;//             } else break;//         }         if (L>=0) {             strcpy(buf+i,ln);i+=MAXCHARS;             n++;             if (n>=MAXLINES) {                 MAXLINES2=MAXLINES*2;                 if (MAXLINES2==1280000) MAXLINES2=2500000;                 buf2=(char *)realloc(buf,MAXLINES2*MAXCHARS);                 if (NULL==buf2) {                     free(buf);                     fclose(fl);                     fclose(fp);                     fprintf(stderr,"Can not malloc(%d LINES*%d CHARS)!\n",MAXLINES2,MAXCHARS);                     return 5;                 }                 buf=buf2;                 MAXLINES=MAXLINES2;             }         }     }     fclose(fl);     if (ignore_case) qsort(buf,n,MAXCHARS,icompare);     else qsort(buf,n,MAXCHARS,compare);     hh=0;     while (1) {         if (fgets(ln,MAXCHARS,fp)==NULL) break;//         hh++;         L=strlen(ln)-1;         if ('\n'!=ln[L]) {//超长行忽略后面内容             fprintf(stderr,"%s Line %d too long(>%d),spilth ignored.\n",PROG,hh,MAXCHARS);             while (1) {                 c=fgetc(fp);                 if ('\n'==c || EOF==c) break;//             }         }         while (1) {//去掉行尾的'\n'和空格             if ('\n'==ln[L] || ' '==ln[L]) {                 ln[L]=0;                 L--;                 if (L<0) break;//             } else break;//         }         if (L>=0) {             if (ignore_case) {                 if (NULL==bsearch(ln,buf,n,MAXCHARS,icompare)) printf("%s\n",ln);             } else {                 if (NULL==bsearch(ln,buf,n,MAXCHARS,compare)) printf("%s\n",ln);             }         }     }     fclose(fp);     free(buf);     return 0; }

user: user-2
content: 楼主realloc返回NULL就不怕原先那块内存没释放吗？

user: user-1
content: CreateFileMapping The CreateFileMapping function creates a named or unnamed file-mapping object for the specified file.   HANDLE CreateFileMapping(   HANDLE hFile,              // handle to file to map   LPSECURITY_ATTRIBUTES lpFileMappingAttributes,                              // optional security attributes   DWORD flProtect,           // protection for mapping object   DWORD dwMaximumSizeHigh,   // high-order 32 bits of object size   DWORD dwMaximumSizeLow,    // low-order 32 bits of object size   LPCTSTR lpName             // name of file-mapping object );

user: user-1
content: GlobalMemoryStatusVlm [This is preliminary documentation and subject to change.]   The GlobalMemoryStatusVlm function obtains information about the computer's current usage of both physical and virtual memory.   VOID GlobalMemoryStatusVlm(   LPMEMORYSTATUSVLM lpBuffer   // pointer to a memory status structure );   Parameters lpBuffer  Pointer to a MEMORYSTATUSVLM structure. GlobalMemoryStatusVlm stores information about current memory availability in this structure.  Return Values This function does not return a value.   Remarks You can use the GlobalMemoryStatusVlm function to determine how much memory your application can allocate without severely impacting other applications.   The information returned by the GlobalMemoryStatusVlm function is volatile. There is no guarantee that two sequential calls to this function will return the same information.   QuickInfo   Windows NT: Requires version 5.0 or later.   Windows: Unsupported.   Windows CE: Unsupported.   Header: Declared in winbase.h.   Import Library: Use kernel32.lib.  See Also Memory Management Overview, Memory Management Functions, Very Large Memory (VLM), GlobalMemoryStatus, MEMORYSTATUSVLM

user: user-3
content: 不断在同样的地址扩增空间，这样的做法不太好吧？这样比重新malloc失败的几率会越来越大

user: user-4
content: 提问能力决定了工作能力

user: user-5
content: 动态申请内存总是有机会不成功的。  引用 楼主 wbct007 的回复:如何避免realloc申请空间过大？一个buff，不断的realloc，每次加固定长度，但是几次之后就会提示  realloc(): invalid next size: 0x00007f7af426e610   我知道是因为内存不够，但是，如何避免？  realloc申请内存失败以后，原ptr不变，大小也不变，但是，这个size有问题，怎么避免？

user: user-0
content: 原程序

user: user-0
content: 好吧，实践证明随着运行时间的延长，性能下降很厉害呀，内存泄露估计是存在的，这个，优化……

user: user-6
content: 个人能从来都是建议以及尽量不用这个函数的！ 很多问题