关于realloc和free

yiyefangzhou24 2014-03-17 01:21:43
我这么写一个函数

char * function1()
{
char * p;
p=(char *)malloc(x);
p=(char *)realloc(p,x+y);
return p;
}
void main()
{
char * p;
p=function1();
free(p);
}

这个函数在free的时候概率性出错,错误是内存越界,请问为什么?错在哪里呢?
...全文
168 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2014-03-17
  • 打赏
  • 举报
回复
引用 11 楼 zhao4zhong1 的回复:
[quote=引用 9 楼 yiyefangzhou24 的回复:] 找到原因了,realloc少分配了一个字节,最后的\0,这个函数心有余悸啊,擦
“多一少一”问题占程序员常犯错误的10%以上! [/quote] 避免“多一少一”问题的方法之一是将比如≤10甚至≤5的数代入程序片断,搬手指头心算验证一下程序到底应该写为 x、x-1、x+1中的哪个? <、<=、==、>、>=中的哪个?
赵4老师 2014-03-17
  • 打赏
  • 举报
回复
引用 9 楼 yiyefangzhou24 的回复:
找到原因了,realloc少分配了一个字节,最后的\0,这个函数心有余悸啊,擦
“多一少一”问题占程序员常犯错误的10%以上!
赵4老师 2014-03-17
  • 打赏
  • 举报
回复
请判断每个函数的返回值!
yiyefangzhou24 2014-03-17
  • 打赏
  • 举报
回复
找到原因了,realloc少分配了一个字节,最后的\0,这个函数心有余悸啊,擦
yiyefangzhou24 2014-03-17
  • 打赏
  • 举报
回复
free(p); return NULL; 更正楼上笔误,顺序反了
yiyefangzhou24 2014-03-17
  • 打赏
  • 举报
回复
额。。。
char * function1()
{
       char * p;char * p2;
       p=(char *)malloc(x);
       p2=(char *)realloc(p,x+y);
       if(p2==NULL)
       {
             return NULL;
             free(p);
       }
       p=p2;
       return p;
}
void main()
{
      char * p;
      p=function1();
      if(p!=NULL)
          free(p);
}
这样还是有错,我觉得我realloc的写法没错吧?
赵4老师 2014-03-17
  • 打赏
  • 举报
回复
MALLOC Section: Linux Programmer's Manual (3 ) Updated: 1993-04-04 -------------------------------------------------------------------------------- NAME calloc, malloc, free, realloc - Allocate and free dynamic memory SYNOPSIS #include <stdlib.h> void *calloc(size_t nmemb, size_t size); void *malloc(size_t size); void free(void *ptr); void *realloc(void *ptr, size_t size); DESCRIPTION calloc() allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. malloc() allocates size bytes and returns a pointer to the allocated memory. The memory is not cleared. free() frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is NULL, no operation is performed. realloc() changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged to the minimum of the old and new sizes; newly allocated memory will be uninitialized. If ptr is NULL, the call is equivalent to malloc(size); if size is equal to zero, the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc(). If the area pointed to was moved, a free(ptr) is done. RETURN VALUE For calloc() and malloc(), the value returned is a pointer to the allocated memory, which is suitably aligned for any kind of variable, or NULL if the request fails. free() returns no value. realloc() returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails. If size was equal to 0, either NULL or a pointer suitable to be passed to free() is returned. If realloc() fails the original block is left untouched - it is not freed or moved. CONFORMING TO ANSI-C SEE ALSO brk(2), posix_memalign(3) NOTES The Unix98 standard requires malloc(), calloc(), and realloc() to set errno to ENOMEM upon failure. Glibc assumes that this is done (and the glibc versions of these routines do this); if you use a private malloc implementation that does not set errno, then certain library routines may fail without having a reason in errno. Crashes in malloc(), free() or realloc() are almost always related to heap corruption, such as overflowing an allocated chunk or freeing the same pointer twice. Recent versions of Linux libc (later than 5.4.23) and GNU libc (2.x) include a malloc implementation which is tunable via environment variables. When MALLOC_CHECK_ is set, a special (less efficient) implementation is used which is designed to be tolerant against simple errors, such as double calls of free() with the same argument, or overruns of a single byte (off-by-one bugs). Not all such errors can be protected against, however, and memory leaks can result. If MALLOC_CHECK_ is set to 0, any detected heap corruption is silently ignored; if set to 1, a diagnostic is printed on stderr; if set to 2, abort() is called immediately. This can be useful because otherwise a crash may happen much later, and the true cause for the problem is then very hard to track down. BUGS By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. This is a really bad bug. In case it turns out that the system is out of memory, one or more processes will be killed by the infamous OOM killer. In case Linux is employed under circumstances where it would be less desirable to suddenly lose some randomly picked processes, and moreover the kernel version is sufficiently recent, one can switch off this overcommitting behavior using a command like # echo 2 > /proc/sys/vm/overcommit_memory See also the kernel Documentation directory, files vm/overcommit-accounting and sysctl/vm.txt. --------------------------------------------------------------------------------
赵4老师 2014-03-17
  • 打赏
  • 举报
回复
REALLOC Section: POSIX Programmer's Manual (P) Updated: 2003 -------------------------------------------------------------------------------- NAME realloc - memory reallocator SYNOPSIS #include <stdlib.h> void *realloc(void *ptr, size_t size); DESCRIPTION The realloc() function shall change the size of the memory object pointed to by ptr to the size specified by size. The contents of the object shall remain unchanged up to the lesser of the new and old sizes. If the new size of the memory object would require movement of the object, the space for the previous instantiation of the object is freed. If the new size is larger, the contents of the newly allocated portion of the object are unspecified. If size is 0 and ptr is not a null pointer, the object pointed to is freed. If the space cannot be allocated, the object shall remain unchanged. If ptr is a null pointer, realloc() shall be equivalent to malloc() for the specified size. If ptr does not match a pointer returned earlier by calloc(), malloc(), or realloc() or if the space has previously been deallocated by a call to free() or realloc(), the behavior is undefined. The order and contiguity of storage allocated by successive calls to realloc() is unspecified. The pointer returned if the allocation succeeds shall be suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object in the space allocated (until the space is explicitly freed or reallocated). Each such allocation shall yield a pointer to an object disjoint from any other object. The pointer returned shall point to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null pointer shall be returned. RETURN VALUE Upon successful completion with a size not equal to 0, realloc() shall return a pointer to the (possibly moved) allocated space. If size is 0, either a null pointer or a unique pointer that can be successfully passed to free() shall be returned. If there is not enough available memory, realloc() shall return a null pointer and set errno to [ENOMEM]. ERRORS The realloc() function shall fail if: ENOMEM Insufficient memory is available. The following sections are informative. EXAMPLES None. APPLICATION USAGE None. RATIONALE None. FUTURE DIRECTIONS None. SEE ALSO calloc() , free() , malloc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h> COPYRIGHT Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html . --------------------------------------------------------------------------------
赵4老师 2014-03-17
  • 打赏
  • 举报
回复
realloc Reallocate memory blocks. void *realloc( void *memblock, size_t size ); Routine Required Header Compatibility realloc <stdlib.h> and <malloc.h> ANSI, Win 95, Win NT For additional compatibility information, see Compatibility in the Introduction. Libraries LIBC.LIB Single thread static library, retail version LIBCMT.LIB Multithread static library, retail version MSVCRT.LIB Import library for MSVCRT.DLL, retail version Return Value realloc returns a void pointer to the reallocated (and possibly moved) memory block. The return value is NULL if the size is zero and the buffer argument is not NULL, or if there is not enough available memory to expand the block to the given size. In the first case, the original block is freed. In the second, the original block is unchanged. The return value points to a storage space that is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than void, use a type cast on the return value. Parameters memblock Pointer to previously allocated memory block size New size in bytes Remarks The realloc function changes the size of an allocated memory block. The memblock argument points to the beginning of the memory block. If memblock is NULL, realloc behaves the same way as malloc and allocates a new block of size bytes. If memblock is not NULL, it should be a pointer returned by a previous call to calloc, malloc, or realloc. The size argument gives the new size of the block, in bytes. The contents of the block are unchanged up to the shorter of the new and old sizes, although the new block can be in a different location. Because the new block can be in a new memory location, the pointer returned by realloc is not guaranteed to be the pointer passed through the memblock argument. realloc calls malloc in order to use the C++ _set_new_mode function to set the new handler mode. The new handler mode indicates whether, on failure, malloc is to call the new handler routine as set by _set_new_handler. By default, malloc does not call the new handler routine on failure to allocate memory. You can override this default behavior so that, when realloc fails to allocate memory, malloc calls the new handler routine in the same way that the new operator does when it fails for the same reason. To override the default, call _set_new_mode(1) early in your program, or link with NEWMODE.OBJ. When the application is linked with a debug version of the C run-time libraries, realloc resolves to _realloc_dbg. For more information about how the heap is managed during the debugging process, see Using C Run-Time Library Debugging Support. Example /* REALLOC.C: This program allocates a block of memory for * buffer and then uses _msize to display the size of that * block. Next, it uses realloc to expand the amount of * memory used by buffer and then calls _msize again to * display the new amount of memory allocated to buffer. */ #include <stdio.h> #include <malloc.h> #include <stdlib.h> void main( void ) { long *buffer; size_t size; if( (buffer = (long *)malloc( 1000 * sizeof( long ) )) == NULL ) exit( 1 ); size = _msize( buffer ); printf( "Size of block after malloc of 1000 longs: %u\n", size ); /* Reallocate and show new size: */ if( (buffer = realloc( buffer, size + (1000 * sizeof( long )) )) == NULL ) exit( 1 ); size = _msize( buffer ); printf( "Size of block after realloc of 1000 more longs: %u\n", size ); free( buffer ); exit( 0 ); } Output Size of block after malloc of 1000 longs: 4000 Size of block after realloc of 1000 more longs: 8000 Memory Allocation Routines See Also calloc, free, malloc
yiyefangzhou24 2014-03-17
  • 打赏
  • 举报
回复
况且我按照你这么写在main函数free(p);的时候还是会出错
yiyefangzhou24 2014-03-17
  • 打赏
  • 举报
回复
引用 1 楼 zhao4zhong1 的回复:
仅供参考
//输出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;
}
赵大叔,你这段之前我看过了。 buf2=(char *)realloc(buf,MAXLINES2*MAXCHARS); if (NULL==buf2) { free(buf); ..... } buf=buf2; 这个地方是不是一定要这么用,我看很多资料上都是直接p=(char *)realloc(p,x+y);我忘了写了,我上面代码会判断一下 p=function1(); if(p!=NULL) free(p); realloc这里在分配内存的时候不是已经把第一个参数的那个指针处理过了(free)为什么还要手动free?
赵4老师 2014-03-17
  • 打赏
  • 举报
回复
仅供参考
//输出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;
}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧