小c程序basic.returning指针

Vij*_*jay 1 c pointers

我总是怀疑这个疑问.请看以下程序:

#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中分配的内存?

ins*_*ity 7

记忆泄漏

你是因为你的代码没有泄漏任何内存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)

您应该看到两个打印(chtemp)将打印相同的地址.因此,free(ch);free正确的malloced大块内存.

您也可以使用valgrind检查您的代码是否未free分配内存.

关于警告

功能free,malloc根据已确定stdlib.h.

在您的代码中添加:

#include <stdlib.h>
#include <stdio.h>
...
Run Code Online (Sandbox Code Playgroud)

此外,投射malloc回报值并不是一个好主意temp=(char *)malloc(...);.请在这里阅读.