我总是怀疑这个疑问.请看以下程序:
#include <stdio.h>
char * function1(void);
int main()
{
char *ch;
ch = function1();
printf("hello");
free(ch);
return 0;
}
char* function1()
{
char *temp;
temp = (char *)malloc(sizeof(char)*10);
return temp;
}
Run Code Online (Sandbox Code Playgroud)
我在这里泄漏记忆吗?该程序不会因为某些警告而崩溃:
prog.c: In function ‘main’:
prog.c:11: warning: implicit declaration of function ‘free’
prog.c:11: warning: incompatible implicit declaration of built-in function ‘free’
prog.c: In function ‘function1’:
prog.c:19: warning: implicit declaration of function ‘malloc’
prog.c:19: warning: incompatible implicit declaration of built-in function ‘malloc’
Run Code Online (Sandbox Code Playgroud)
打印你好.
我只是C.so的初学者请帮助我理解在function1.does中返回语句之后发生了什么真的释放了funtion1中分配的内存?
你是因为你的代码没有泄漏任何内存free(ch);
,其free
被分配的内存malloc
里面function1
的功能.你可以通过打印指针地址来检查这一点,即:
char* function1()
{
char *temp;
temp=(char *)malloc(sizeof(char)*10);
printf("temp: %p\n", temp);
return temp;
}
Run Code Online (Sandbox Code Playgroud)
和
ch = function1();
printf("ch: %p\n", ch);
Run Code Online (Sandbox Code Playgroud)
您应该看到两个打印(ch
和temp
)将打印相同的地址.因此,free(ch);
将free
正确的malloc
ed大块内存.
您也可以使用valgrind检查您的代码是否未free
分配内存.
功能free
,malloc
根据已确定stdlib.h
.
在您的代码中添加:
#include <stdlib.h>
#include <stdio.h>
...
Run Code Online (Sandbox Code Playgroud)
此外,投射malloc
回报值并不是一个好主意temp=(char *)malloc(...);
.请在这里阅读.
归档时间: |
|
查看次数: |
891 次 |
最近记录: |