• C语言,题目:函数调用,内存,malloc找错


      

    malloc

    int* p = (int *) malloc (sizeof(int)*128);

    //分配128个(可根据实际需要替换该数值)整型存储单元,并将这128个连续的整型存储单元的首地址存储到指针变量p中.

    在Linux中可以有这样:malloc(0),这是因为Linux中malloc有一个下限值16Bytes,注意malloc(-1)是禁止的;但是在某些系统中是不允许malloc(0)的。

    if (NULL == (p = (type *)malloc(sizeof (type)))) /*请使用if来判断,这是有必要的*/

    函数:函数传参:值传递,单向传递,拷贝传递。

    void GetMemory(char *p)

    {

    p = (char *)malloc(100);

    }

    void Test(void)

    {

    char *str = NULL;

    GetMemory(str);

    //值传递,单向传递,拷贝传递。

    strcpy(str, "hello world");

    printf(str);

    }

    str不能获得p所指向的内存空间,形参值的改变不会影响实参值;并且malloc开辟的堆空间最后没有释放。

     

    char *GetMemory(void)

    {   

    char p[] = "hello world";

    return p;

    //p:数组,栈空间;

    //运行char p[] = "hello world"后,会开辟1块内存。完毕后空间和数据都释放。

    }

    void Test(void)

    {

    char *str = NULL;

    str = GetMemory();

    //空间被释放掉了

    printf(str);

    }

     str不能获得p所指向的内存空间,错在子函数返回了一个指向栈空间的指针,该栈空间在函数调用结束之后就被系统回收了,p所指向的栈数组空间内的”hello world”可能已经被系统销毁了

    Void GetMemory(char **p, int num)

    {

    *p = (char *)malloc(num);

    }

    void test(void)

    {

    char *str = NULL;

    GetMemory(&str, 100);

    strcpy(str, "hello");   

    printf(str);   

    }

    //可以打印出”hello, 只是malloc开辟的堆空间最后没有释放。

    void test(void)

    {

    char *str = (char *) malloc(100);

    strcpy(str, “hello”);

    free(str);       

    if(str != NULL)

    {

    strcpy(str, “world”);

    //不能操作已经被释放的堆空间

    printf(str);

    }

    }

    //错在堆空间已经释放掉了却仍在使用指向堆空间的指针。

    void fun(char* str1, char* str2)

    {

    *str1 = *str2;

    }

    main()

    {

    char *str1="ABC ";

    char *str2="BCD ";

    fun(str1, str2)//都是只读的,段错误。

    printf(str1);

    }

    错在通过指针修改字符常量区的内容

    void f1(char *p)

    {

    p = (char *)malloc(100);

    }

    int test()

    {

    char *str = NULL;

    f1(&str);//传参类型不匹配

    strcpy(str, "hello world");

    printf(str);

    }

    //传参类型不匹配并且malloc开辟的堆空间最后没有释放

  • 相关阅读:
    《你又怎么了我错了行了吧》【Alpha】Scrum meeting 4
    《你又怎么了我错了行了吧》【Alpha】Scrum meeting 3
    《你又怎么了我错了行了吧》【Alpha】Scrum meeting 2
    《你又怎么了我错了行了吧》第八次团队作业:Alpha冲刺
    《你又怎么了我错了行了吧》【Alpha】Scrum meeting 1
    【Beta】 Scrum meeting 3
    【Beta】Scrum meeting 2
    【Beta】Scrum Meeting 1
    实验十三 团队作业9:BETA冲刺与团队项目验收
    实验十二 团队作业8:软件测试与Alpha冲刺 第五天
  • 原文地址:https://www.cnblogs.com/mylinux/p/4667738.html
Copyright © 2020-2023  润新知