回 帖 发 新 帖 刷新版面

主题:内存错误问题请求解答

code=c]
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
char *my_strcpy(char *source)
{
   char *target=(char *)malloc(sizeof(char));
    if (NULL == target) 
    { 
        exit(1); 
    } 
   for(int i=0;i<strlen(source);i++)
   {
       *(target+i)=*(source+i);
   }
   *(target+i)='\0';
   return target;
}


int main()
{
   char *source=(char *)malloc(sizeof(char));
   if (NULL == source) 
    { 
        exit(1); 
    } 
   source="asdfgh";
   printf("%s\n",my_strcpy(source));
   free(source);
   source = NULL; 

   return 0;
}
/*]
*   运行到最后释放主函数里的source的内存时出错,为什么?
*       char *my_strcpy(char *source)里的target所申请的内存空间应该也要手动释放吧,那怎么释放呢??就是free()语句写在什么地方啊,还是系统自动在调用函数结束后自动释放啊?
小弟初学,请求大家的帮助,谢谢

*/
[/code]

回复列表 (共2个回复)

沙发

首先,你的程序有个本质错误,就是你只给字符指针申请了一个字符的空间却企图写入更多内容
其次,当你做source="asdfgh";的时候,注意你的source指针已经不再指向malloc的结果了,而是指向为常量"asdfgh"临时开辟的内存,这个内存当然是无法释放的了。至于你的target,因为要return,自然不能free

板凳


[code=c]
 char *target=(char *)malloc(sizeof(char)); // 使用 strlen(source)

 char *source=(char *)malloc(sizeof(char)); // 和下面几句都没有实际意义
   if (NULL == source) 
    { 
        exit(1); 
    } [/code]

我来回复

您尚未登录,请登录后再回复。点此登录或注册