2014-02-13 39 views
0

我的代碼給了我一個分段錯誤。我99%肯定這個錯誤來源於我糟糕的代碼構造。在我的代碼中獲取分段錯誤

#include <stdio.h> 
#include <assert.h> 
#include <string.h> 

int decToBit(unsigned int I, char *str){ 

     str = ""; 
     int currentVal = I; 

     do{ 
       if(I%2 == 0) 
         strcat(str,"0"); 
       else 
         strcat(str,"1"); 

       } while(currentVal > 0); 

     return(0); 
} 
+1

通過這樣做'STR = 「」;','decToBit()'忽略str'的​​'原始值。可能希望'str [0] ='\ 0''; – chux

+0

http://stackoverflow.com/questions/13273623/c-structure-member-is-a-string-how-to-assign-bytes-directly/13273656#13273656 – Jeyaram

+0

@chux哇真棒建議,你是一個生命保護程序。我的代碼終於跑了 – InfoSecNoob

回答

2

你需要確保有在str足夠的空間來增加額外的字符:

char myStr[200]; 
myStr[0] = '\0'; // make sure you start with a "zero length" string. 
strcpy(myStr, str); 

,然後你在哪裏使用str使用myStr

正因爲如此,該語句

str=""; 

strconst char* - 這是你能讀不能寫一個字符串。

順便主呼叫簽名

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

換句話說,你需要一個指向字符指針。如果我沒有弄錯,你想要做以下的事情(這裏有一些介紹):

每一個奇數的參數都會得到1加1;每個偶數參數都會被添加一個0。

如果我讀心技巧的工作,那麼你可能想試試這個:

#include <stdio.h> 
#include <string.h> 

int main(int argc, char * argv[]) { 
    char temp[200]; 
    temp[0] = '\0'; 
    int ii; 

    for(ii = 0; ii < argc; ii++) { 
    strncpy(temp, argv[ii], 200); // safe copy 
    if(ii%2==0) { 
     strcat(temp, "0"); 
    } 
    else { 
     strcat(temp, "1"); 
    } 
    printf("%s\n", temp); 
    } 
} 

編輯剛剛意識到你編輯的問題,現在你的目的是更清晰。

修改你的函數一點:

int decToBit(unsigned int I, char *str){ 

    str[0] = '\0'; 
    char *digit; 
    do 
    { 
    digit = "1"; 
    if (I%2 == 0) digit = "0"; 
    strcat(str, digit); 
    I>>=1; 
    } while (I != 0); 

    return(0); 
} 

看來工作...

+0

我對此沒有明確表示歉意,但是這種方法是從主類 – InfoSecNoob

+0

「主要類」接收一個str和它的大小?你把它標記爲'C'。而且你有一個'main'函數......好吧,看看我更新的答案對你有用。 – Floris

+1

是的,非常非常感謝 – InfoSecNoob

1

在do-while循環,你應該增加currentVal的價值。否則,它將是一個無限循環,最終會出現分段錯誤。

+0

無限循環是一個問題,但本身不應該導致分段錯誤。 – Xymostech

+1

@Xymostech - 它最終會繼續附加到一個字符串。 – Floris

+0

謝謝你指出這個錯誤。 – InfoSecNoob

1

正確初始化str[0]
除以2每個循環我。

但是,然後該字符串將以小尾序。懷疑是有意的嗎?

int decToBit(unsigned int I, char *str) { 
    str[0] = '\0'; 
    do { 
    if (I%2 == 0) 
     strcat(str,"0"); 
    else 
     strcat(str,"1"); 
    I /= 2; 
    } while(I > 0); 
    return(0); 
} 

// call example 
char buf[sizeof(unsigned)*CHAR_BIT + 1]; 
decToBit(1234567u, buf); 
+0

啊=你認爲我們正在嘗試創建一個二進制數?這改變了一切... – Floris

+1

@弗洛里斯是的,但它似乎是OP做一點點endian命令。也許這將是下一篇文章? – chux

+0

由於OP無法讓您的答案upvote,我會。也許他會弄清楚如何接受一個答案不久?... – Floris

0
#include <stdio.h> 
#include <string.h> 
#include <limits.h> 
#include <assert.h> 

char *decToBit(unsigned int I, char *str){ 
    int bit_size = CHAR_BIT * sizeof(I); 
    str += bit_size; 
    *str = 0; 
    do{ 
     *--str = "01"[I & 1]; 
    }while(I>>=1); 
    return str; 
} 

int main(){ 
    char bits[33]; 
    printf("%s\n", decToBit(0, bits)); 
    printf("%s\n", decToBit(-1, bits)); 
    printf("%s\n", decToBit(5, bits)); 
    return 0; 
}