[問題] 關於function中malloc問題
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
DEV C
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
在我的strcpy中,我選擇在function中使用malloc配置記憶體,如此情況下
程式會出錯,但如果我是在main中使用malloc,則程式可以正常的執行my_strcpy,
還請各位版友告訴我問題在哪裡。
餵入的資料(Input):
預期的正確結果(Expected Output):
錯誤結果(Wrong Output):
程式碼(Code):(請善用置底文網頁, 記得排版)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* my_strcpy(char* dst, const char* src)
{
dst=malloc(sizeof(char)*10); //malloc in function
char* ret= dst;
while(*ret++ = *src++);
return ret;
}
void my_str_print(char * my_string)
{
int i;
for( i=0; i<strlen(my_string); i++)
{
printf("%c",my_string[i]);
}
}
int main ()
{
char str1[]="abcde";
//char* str2=malloc(sizeof(char)*10); //malloc in main
char* str2;
printf("the address:%X\n",str2);
my_strcpy(str2,str1);
my_str_print(str2);
system("PAUSE");
free(str2);
return 0;
}
補充說明(Supplement):
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 219.84.27.29
推
02/09 03:09, , 1F
02/09 03:09, 1F
→
02/09 08:17, , 2F
02/09 08:17, 2F
→
02/09 09:56, , 3F
02/09 09:56, 3F
推
02/09 11:23, , 4F
02/09 11:23, 4F
→
02/09 11:51, , 5F
02/09 11:51, 5F
→
02/09 11:51, , 6F
02/09 11:51, 6F
→
02/09 11:53, , 7F
02/09 11:53, 7F
→
02/09 11:54, , 8F
02/09 11:54, 8F
→
02/09 12:07, , 9F
02/09 12:07, 9F
推
02/09 12:25, , 10F
02/09 12:25, 10F
→
02/09 13:13, , 11F
02/09 13:13, 11F
→
02/09 13:14, , 12F
02/09 13:14, 12F
→
02/09 13:14, , 13F
02/09 13:14, 13F
→
02/09 13:16, , 14F
02/09 13:16, 14F
→
02/09 13:17, , 15F
02/09 13:17, 15F
→
02/09 13:37, , 16F
02/09 13:37, 16F
→
02/09 15:12, , 17F
02/09 15:12, 17F
→
02/09 15:13, , 18F
02/09 15:13, 18F
→
02/09 15:15, , 19F
02/09 15:15, 19F
→
02/09 15:16, , 20F
02/09 15:16, 20F
→
02/09 16:00, , 21F
02/09 16:00, 21F
→
02/09 16:26, , 22F
02/09 16:26, 22F
推
02/09 17:13, , 23F
02/09 17:13, 23F
推
02/09 17:57, , 24F
02/09 17:57, 24F
→
02/09 17:59, , 25F
02/09 17:59, 25F
→
02/09 18:37, , 26F
02/09 18:37, 26F
→
02/09 19:46, , 27F
02/09 19:46, 27F
推
02/09 20:51, , 28F
02/09 20:51, 28F
→
02/09 21:08, , 29F
02/09 21:08, 29F
→
02/09 22:17, , 30F
02/09 22:17, 30F
→
02/10 01:19, , 31F
02/10 01:19, 31F
→
02/10 01:20, , 32F
02/10 01:20, 32F
→
02/10 01:20, , 33F
02/10 01:20, 33F
→
02/10 09:05, , 34F
02/10 09:05, 34F
推
02/10 10:12, , 35F
02/10 10:12, 35F
→
02/10 10:13, , 36F
02/10 10:13, 36F
→
02/10 10:16, , 37F
02/10 10:16, 37F
→
02/10 10:42, , 38F
02/10 10:42, 38F
→
02/10 22:58, , 39F
02/10 22:58, 39F