指針傳遞內存深入探討(三)

 讓我們繼續前兩次的討論

我們同樣可以使用把指針作爲返回值的方法來傳遞內存,而且我個人認爲這是值得推薦的方式

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)"

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章