指针传递内存深入探讨(三)

来源:互联网 发布:英语辅导软件 编辑:程序博客网 时间:2024/04/29 00:31

 让我们继续前两次的讨论

我们同样可以使用把指针作为返回值的方法来传递内存,而且我个人认为这是值得推荐的方式

c代码:

char *GetMemory3(int num)
{
 char *p = (char *)malloc(sizeof(char)*num);
 return p;
}

int main()
{
 char *str = NULL;
 str = GetMemory3(100);
 strcpy(str, "hello");
 printf("%s", str);
 free(str);
}
查看汇编结果如下:

GetMemory3函数:

 .file "getmemory3.c"
 .text
 .align 2
.globl GetMemory3
 .type GetMemory3,@function
GetMemory3:
 pushl %ebp
 movl %esp, %ebp
 subl $8, %esp
 subl $12, %esp
 pushl 8(%ebp)
 call malloc
 addl $16, %esp
 movl %eax, -4(%ebp)
 movl -4(%ebp), %eax
 leave
 ret
.Lfe1:
 .size GetMemory3,.Lfe1-GetMemory3
 .section .rodata

main函数:


.LC0:
 .string "hello"
.LC1:
 .string "%s"
 .text
 .align 2
.globl main
 .type main,@function
main:
 pushl %ebp
 movl %esp, %ebp
 subl $8, %esp
 andl $-16, %esp
 movl $0, %eax
 subl %eax, %esp
 movl $0, -4(%ebp)
 subl $12, %esp
 pushl $100
 call GetMemory3
 addl $16, %esp
 movl %eax, -4(%ebp)
 subl $8, %esp
 pushl $.LC0
 pushl -4(%ebp)
 call strcpy
 addl $16, %esp
 subl $8, %esp
 pushl -4(%ebp)
 pushl $.LC1
 call printf
 addl $16, %esp
 subl $12, %esp
 pushl -4(%ebp)
 call free
 addl $16, %esp
 leave
 ret
.Lfe2:
 .size main,.Lfe2-main
 .ident "GCC: (GNU) 3.2 20020903 (Red Hat Linux 8.0 3.2-7)"

 

原创粉丝点击