编译成功却不能运行?

dongpoyezi 2005-11-09 10:34:17
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


#define null 0;
void mem_cpy(char *s)
{
s=(char*)malloc(100);

}
void main()
{
char *p;
p = null;
char *t ="sdfasdfasdf";


mem_cpy(p);
strcpy(p,t);
printf("%s",p);

}
把t所指的内容附给p所指的内存区域
编译通过不能运行
为什么?
如何修改?
...全文
227 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
Flood1984 2005-11-10
  • 打赏
  • 举报
回复
做为一个程序设计者,
我们希望看到的是编译错误,
要防止编译通过却运行失败。
垄山小站 2005-11-10
  • 打赏
  • 举报
回复
to elvispl(Elvis)
进程都结束了,还内存泄漏什么呀
还少了个free操作对吧
elvispl 2005-11-10
  • 打赏
  • 举报
回复
这样的值传递问题难道不会造成内存泄漏吗?
cdo 2005-11-10
  • 打赏
  • 举报
回复
还是用指向指针的指针吧。
垄山小站 2005-11-10
  • 打赏
  • 举报
回复
楼上,这不是内存泄漏, 函数的值传递问题

垄山小站 2005-11-10
  • 打赏
  • 举报
回复
p=0, s=p, s=0; s=(char*)malloc(100), 比如s=1了; 此时 p还是等于0;
lzp229 2005-11-10
  • 打赏
  • 举报
回复
这个是传说中的内存泄漏吧。
hbvanguard 2005-11-10
  • 打赏
  • 举报
回复
这样也可以:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include "stdlib.h"

#define null 0;
char* mem_cpy(char *s)
{
s=(char*)malloc(100);
return s;
}
void main()
{
char *p;
p = null;
char *pp=null;
char *t ="sdfasdfasdf";


pp=mem_cpy(p);
strcpy(pp,t);
printf("%s",pp);

}
s_topman 2005-11-10
  • 打赏
  • 举报
回复
记住:
C的参数传递是:“值传”
屋顶上的老猫 2005-11-10
  • 打赏
  • 举报
回复
void mem_cpy(char *s)
{
s=(char*)malloc(100);

}
运行mem_cpy(p),并不是为p分配了100内存,它实际给形参s做了分配。而我们真正要分配的p一无所有,一般分配内存的时候一定要一对一的方式。

p=(char *)malloc(sizeof(..));
goodluckyxl 2005-11-10
  • 打赏
  • 举报
回复
是的 c中不能用引用
char* mem_cpy()
{
return (char*)malloc(100);

}
csucdl 2005-11-10
  • 打赏
  • 举报
回复
void mem_cpy(char **s)
{
*s=(char*)malloc(100);
}
mem_cpy(&p);
qmxy 2005-11-10
  • 打赏
  • 举报
回复
同意1楼和3楼,2楼的不对,4楼里的引用好象在C中是不能用的吧,用在C++里可以
goodluckyxl 2005-11-10
  • 打赏
  • 举报
回复
void mem_cpy(char *&s) //here use pointer reference is ok
{
s=(char*)malloc(100);

}
fiftymetre 2005-11-09
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


#define null 0;
void mem_cpy(char **s)
{
*s=(char*)malloc(100);

}
void main()
{
char *p;
p = null;
char *t ="sdfasdfasdf";


mem_cpy(&p);
strcpy(p,t);
printf("%s",p);

}
lisiyong 2005-11-09
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


#define null 0;
void mem_cpy(char *s)
{
s=(char*)malloc(100);

}
void main()
{
char *p;
p = null;
char *t ="sdfasdfasdf\0";


mem_cpy(p);
strcpy(p,t);
printf("%s",p);

}
JohnTitor 2005-11-09
  • 打赏
  • 举报
回复
void mem_cpy(char **s)
{
*s=(char*)malloc(100);

}
void main()
{
char *p;
p = null;
char *t ="sdfasdfasdf";


mem_cpy(&p);
strcpy(p,t);
printf("%s",p);

}

69,371

社区成员

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

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