免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1435 | 回复: 5
打印 上一主题 下一主题

一段代码 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-04-06 19:45 |只看该作者 |倒序浏览
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>

char * testfunction();

int main( void )
{
    char *temp = testfunction();
    printf( "%d\n" , strcmp( temp , "asdf" ) );
    printf( "%s" ,temp );
    system("pause");
    return 0;

}

char * testfunction()
{
    char *t=(char *)alloca(23);
    strcpy( t , "asdf");
    return t;
}


输出
0

论坛徽章:
0
2 [报告]
发表于 2008-04-06 19:54 |只看该作者
原帖由 zzdts 于 2008-4-6 19:45 发表
#include
#include
#include
#include

char * testfunction();

int main( void )
{
    char *temp = testfunction();
    printf( "%d\n" , strcmp( temp , "asdf" ) );
    printf( "%s" ,t ...


这种情况下你就不能用 alloca 来分配空间了,因为 alloca 跟 malloc 不同,alloca 分配的空间是在stack上,而 malloc 是在堆上的。

所以,当testfunction 调用并结束之后,stack被摧毁了,所以出现乱码了,如果是malloc就没事,但是你在main函数最后必须free内存。

论坛徽章:
0
3 [报告]
发表于 2008-04-06 19:54 |只看该作者
alloca引起,请使用alloc

在调用 alloca() 的函数返回的时候, 它分配的内存会自动释放。也就是说, 用 alloca 分配的内存在某种程度上局部于函数的 ``堆栈帧"  或上下文中。

论坛徽章:
0
4 [报告]
发表于 2008-04-06 19:56 |只看该作者
man一下吧:


  1. SYNOPSIS
  2.        #include <alloca.h>

  3.        void *alloca(size_t size);

  4. DESCRIPTION
  5.        The  alloca() function allocates size bytes of space in the stack frame
  6.        of the caller.  This temporary space is automatically  freed  when  the
  7.        function that called alloca() returns to its caller.

复制代码

[ 本帖最后由 LinuxKen 于 2008-4-6 19:57 编辑 ]

论坛徽章:
0
5 [报告]
发表于 2008-04-06 20:05 |只看该作者
哦。谢谢各位

论坛徽章:
0
6 [报告]
发表于 2008-04-06 20:43 |只看该作者
这个帖子很经典哦。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP