【问题标题】:Getting a segmentation fault in my code在我的代码中出现分段错误
【发布时间】:2014-02-13 01:50:24
【问题描述】:

我的代码给了我一个分段错误。我 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);
}

【问题讨论】:

  • 通过str = "";decToBit() 会忽略str 的原始值。可能想要str[0] = '\0';
  • @chux 哇很棒的建议,你是一个救生员。我的代码终于运行了
  • @user2460844 许多人做出了贡献。一旦达到 15 个以上的代表点,请考虑对所有有用的答案进行投票。

标签: c


【解决方案1】:

您需要确保str 中有足够的空间来添加额外的字符:

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

然后在您使用 str 的地方使用 myStr

事实上,声明

str="";

str 指向const char* - 这是一个您可以读取但不能写入的字符串。

顺便说一句,main 的调用签名是

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

换句话说,你需要一个指向char的指针。如果我没记错的话,你想做以下事情(在这里读一点心意):

每个奇数参数都加 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);
  }
}

edit 刚刚意识到您编辑了问题,现在您的目的更加明确了。

稍微修改了你的函数:

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);
}

它似乎工作......

【讨论】:

  • 我很抱歉没有说清楚,但是这个方法是从一个主类接收一个 str 和它的大小
  • “主要课程”?您将此标记为C。而且你有一个main 函数……看看我更新的答案是否对你有用。
【解决方案2】:

在 do-while 循环中,您应该增加 currentVal 的值。否则它将是一个无限循环,最终会出现分段错误。

【讨论】:

  • 无限循环是个问题,但其本身不应导致分段错误。
  • @Xymotech - 如果你继续附加到一个字符串,它最终会。
【解决方案3】:

正确初始化str[0]
每个循环将 I 除以 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);

【讨论】:

  • @Floris 是的,但似乎 OP 正在执行一点字节序。也许这将是下一篇文章?
  • 既然 OP 还不能投票给你的答案,我会的。也许他很快就会弄清楚如何接受答案?...
  • @Floris 同时我可以被你HAL 的眼睛催眠。
  • 你是一个更加催眠的化身!
【解决方案4】:
#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;
}

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 2015-06-22
    相关资源
    最近更新 更多