现在的位置: 首页 > 综合 > 正文

动态分配空间和避免野指针的程序

2013年08月20日 ⁄ 综合 ⁄ 共 852字 ⁄ 字号 评论关闭

动态分配空间和避免野指针的程序

1.环境:

[root@localhost 20120721_1]# cat /proc/version 
Linux version 2.6.32-220.el6.i686 (mockbuild@x86-003.build.bos.redhat.com) (gcc version 4.4.5 20110214 (Red Hat 4.4.5-6) (GCC) ) #1 SMP Wed Nov 9 08:02:18 EST 2011

2.程序:

/*
 *wuxiuwen
 *Dynamic allocate memory space and avoid wild pointer
 *
 */

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(void)
{
        char str1[] = "123456789";
        char str2[] = "45";

        int n = 100;
        int d = 20;
        n += d;

 //     calloc(3,50);//3*malloc(50);
        char *p = (char *)malloc(10*sizeof(char));

 //     p = (char *)realloc(p,n--);

        strcpy(p,"123456789");

        free(p);
        p = NULL;
        if(p != NULL)
        {
                strcpy(p,"abcde");
                printf("%s\n",p);
        }
        //      printf("%p\n",strstr(str1,str2));
}

3.说明

1)动态内存分配:malloc,calloc,realloc等;(另外的进行说明);

2)p指针,此处空间释放后,还进行操作,虽然还有该空间,但是这样操作会产生很大问题,free后,这个指针就变成了野指针。但是该处进行了赋值null,避免了这个情况。

3)这个程序主要说明动态分配空间和释放,同时避免野指针。

抱歉!评论已关闭.