zoukankan      html  css  js  c++  java
  • malloc 需要注意的事项

     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <stdlib.h>
     4 void getmemory(char *p)
     5 {
     6         p=(char *) malloc(100);
     7         strcpy(p,"hello world");
     8 }
     9 
    10 
    11 int main()
    12 {
    13         char *str=NULL;
    14        // str=(char*)malloc(100);    //应该在此处分配空间
    15         getmemory(str);
    16         printf("%s
    ",str);
    17 
    18         free(str);
    19         return 0;
    20 }

    此段程序的目的是在main中定义一个char指针ptr,并将其传入getmemory函数中,传入后,希望分配空间并copy一个字符窜到str中,然后main函数将此字符串输出。

    程序的问题在于,malloc在getmemory函数中分配,在这里分配的是为临时分配,当函数结束后分配的空间将无法找到,虽然没有释放掉内存,因此,运行时出现段错误。

  • 相关阅读:
    云时代架构读后感
    余额宝技术架构读后感
    shiyan
    11111
    编写hdfs文件遇到的问题
    123
    啦啦啦
    Hadoop安装
    js根据银行卡号进行判断属于哪个银行并返回银行卡类型
    git 使用
  • 原文地址:https://www.cnblogs.com/wystan/p/4552239.html
Copyright © 2011-2022 走看看