局部指针变量为什么可以正确返回?

来源:互联网 发布:淘宝夜鹰 编辑:程序博客网 时间:2024/05/22 16:00

作为一个菜鸟级别的程序员,我也知道一句话叫做:不能返回局部指针变量

最近有一个问题困扰了我很久,到底能不能返回局部变量。。局部指针变量。。。

先看下面的代码

#include <stdio.h>#include <stdlib.h>#include <string.h>char *func(){    char *p = (char *)malloc(100);    strcpy(p, "hello");    return p;}int main(){    char *str = NULL;    str = func();    free(str);    strcpy(str, "world");    printf(str);    return 0; }

我一直认为,这样的程序肯定不对,返回局部变量的指针,指针在返回时会被释放,但结果却是可以打印出world的,只是报了一个警告。
这里写图片描述
这是为什么呢?
研究了一下,才知道,return之后指针释放了,但所指向的内存空间还未被分配出去,free不会改变原来指针的指向,此时内存也还未分配,所以strcpy才会成功。

#include <stdio.h>#include <stdlib.h>struct A {    int a; };A* func1() {    A test;    test.a = 100;     return &test;}A* func2() {    A* test = (struct A *)malloc(sizeof(struct A));    test->a = 100;     return test;}int main() {    A* p = NULL, *q = NULL;    p = func1();    printf("%d\n", p->a) ;     q = func2();    printf("%d", q->a);     free(p);     free(q);    system("pause");    return 0;}

这个代码可以输出两个100,是一样的道理。

所以说,返回局部指针变量,可能是会得到正确的结果,但只会在小程序中,程序一大,内存操作多了,就会出错了。