2016-12-04 1 views
-1

戻り値のコードに問題があります。この部分では、戻り値がうまく印刷されています。私は、メインでの戻り値と同様に使用する場合、返されるchar *値

char *getUserName(){ 

char username[50]; 
DWORD username_len = 50; 
GetUserName(username, &username_len); 
char *returnValue=username; 
printf("user: %s\n\n",returnValue); 
return returnValue;} 


char *getSystemName(){ 

TCHAR szComputerName[256]; 
DWORD cchComputerName = 256; 
GetComputerName(szComputerName, &cchComputerName); 
char *returnValue=szComputerName; 
printf("system: %s",returnValue); 
return returnValue;} 

をしかし、それは狂気の事を返す(時にはそれが返すだけでなく、システム名):

int main(){ 
char *userName = getUserName(); 
char *systemName = getSystemName(); 

printf("user: %s \n\n",userName); 
printf("system: %s",systemName); 
return 0;} 
+1

文字列 'username'がスタック上ではなく、ヒープ上に割り当てられ、関数はその値を返されたときに* *かもしれません上書きされる。ヒープ上で( 'malloc'を介して)動的に割り当てるか、呼び出し側でそれを割り当ててポインタを渡す必要があります。 – anol

答えて

2

です

:それを修正する方法は2つあります

char *returnValue=username; 
... 
return returnValue; 

:あなたはgetUserName()にローカル変数へのポインタを返したため、未定義の動作につながりました `無効getUserName(char型のユーザー名[])へchar *getUserName()

1)変更プロトタイプ

あなたはgetUserName

2)プロトタイプchar *getUserName()キープを呼び出す前にバッファusernameを提供する必要がありますが、あなたはmallocにする必要がありますその機能の内側にusernameがあります。また、手動で行う必要がありますfreeusernamemain

+0

'char * getSystemName() 'の同じ誤り –

+0

@WeatherVaneはいまったく同じ間違いです – artm

0

malloc関数を使用して解決しました。どうもありがとう。ここで、新しいコードは次のとおりです。他の機能のための

char *getUserName(){ 
char username[50]; 
DWORD username_len = 50; 
GetUserName(username, &username_len); 

char *returnValue=(char *)malloc(strlen(username)+1); 
strcpy(returnValue,username); 

return returnValue;} 

と同じ

関連する問題