2014-01-29 65 views
0

我是新的C,我今天得到了一個錯誤是:段故障核心轉儲Ç

segmentation fault core dumped 

我用gdb跟蹤代碼,我發現,在這行發生錯誤:

if (!strcmp(user_pass, passwddata->passwd)) 

user_passchar數組,並passwddata結構passwd是結構的成員,這也是一種的C哈日陣列,我試圖更改代碼以

if (!strcmp(user_pass, "ttt")) 

未發生錯誤,所以我想對結構發生錯誤,如果需要更多的代碼,我可以添加它,在這裏我要了解在什麼情況下可以在結構上發生這樣的錯誤?

下面是代碼:

int main(int argc, char *argv[]) { 

mypwent *passwddata; /* this has to be redefined in step 2 */ 
/* see pwent.h */ 

char important[LENGTH] = "***IMPORTANT***"; 

char user[LENGTH]; 
//char *c_pass; //you might want to use this variable later... 
char prompt[] = "password: "; 
char *user_pass; 

sighandler(); 

while (TRUE) { 
    /* check what important variable contains - do not remove, part of buffer overflow test */ 
    printf("Value of variable 'important' before input of login name: %s\n", 
      important); 

    printf("login: "); 
    fflush(NULL); /* Flush all output buffers */ 
    __fpurge(stdin); /* Purge any data in stdin buffer */ 

    if (gets(user) == NULL) /* gets() is vulnerable to buffer */ 
    { 
     exit(0); /* overflow attacks. */ 
    } 
    printf("******************* %s\n",user); 

    /* check to see if important variable is intact after input of login name - do not remove */ 
    printf("Value of variable 'important' after input of login name: %*.*s\n", 
      LENGTH - 1, LENGTH - 1, important); 

    user_pass = getpass(prompt); 
    passwddata = getpwnam(user); 

    printf("^^^^^^^^^^^^^^^^^^^^^^^^^^ %s\n", user_pass); 

    if (passwddata != NULL) { 
     /* You have to encrypt user_pass for this to work */ 
     /* Don't forget to include the salt */ 


     if (!strcmp(user_pass, "ttt")) { 

      printf(" You're in !\n"); 

      /* check UID, see setuid(2) */ 
      /* start a shell, use execve(2) */ 

     } 
    } 
    printf("Login Incorrect \n"); 
} 
return 0; 
} 
+0

「passwddata」或「passwd」無效。 – cnicutar

+0

請添加如何創建user_pass和passwddata的代碼。我懷疑你沒有實例化指針passwddata – AndyG

回答

3

最有可能passwdpasswddataNULL,在後一種情況下,->試圖尊重的NULL指針,因此它的崩潰。

通過改變你的代碼:

if (!strcmp(user_pass, "ttt")) 

您隔離的第一部分,所以你知道user_pass是OK。您可以使用調試器或一些檢查和printf來獲取passwddatapasswd的值以解決問題。


現在您已更新代碼,您知道問題出在passwd。你開始用一個空指針:

mypwent *passwddata; 

後來你設置指針的​​的迴歸,想必這是一個指向你分配一些內存類型mypwent的結構:

passwddata = getpwnam(user); 

你有檢查,以確保passwddata不爲空:

if (passwddata != NULL) { 
    if (!strcmp(user_pass, "ttt")) { 

所以,現在你已經檢查了一切,除了passwd,傳遞nullstrcmp()將導致它與該消息崩潰,所以我猜你只分配內存的結構,而不是爲結構內的char陣列。

+0

我認爲問題是'passwd'是'NULL',順便說一句,你是什麼意思'尊重NULL指針'? –

+0

@ Zhenxiao - 你檢查'if(passwddata!= NULL)'是否會保護你。基本上,如果'getpwnam()'沒有爲你的指針分配內存,''>'操作會崩潰......但就像我說的那樣,這不是基於代碼更新的問題。它必須是'passwd' – Mike

+0

@ Zhenxiao http://www.cprogramming.com/debugging/segfaults.html – Peter

0

我的猜測是passwddata是NULL。

或者緩衝passwddata->passwd

  • 除弦短於user_pass

  • 不是空終止

總之這兩個讓ST rcmp訪問超出第二個參數緩衝區的限制,並因此導致錯誤。