arp*_*ita 2 c unix malloc free
我有下面的代码,它引发了一个分段错误.请建议可以做些什么.
#include <stdio.h>
int main() {
char *p ,*q ;
p =(char *)malloc(20) ;
*p = 30 ;
p++ ;
p=q ;
free(q) ;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢
你正在释放没有返回的东西malloc(q从未初始化).我也能看到你在做什么
p++
Run Code Online (Sandbox Code Playgroud)
在这样做时,你正在失败p,你不能再释放它了.如果你的意思是q=p,这也是无效的.你只能免费malloc返回.
编辑
根据评论,OP 确实打算这样做q = p.你可以这样做:
char *p;
char *save_p;
p = malloc(10); /* stop casting malloc */
save_p = p; /* save the original value of p BEFORE altering it */
/* use p to your heart's content */
free(save_p); /* it's legal to free this */
Run Code Online (Sandbox Code Playgroud)
我看到你问的是关于char与整数的问题.一样的:
free返回确切的值malloc.