简体   繁体   中英

How to fix Segmentation fault (core dumped) error in C

I am building a program that converts hex to binary and I am using char for this because later in my program I need to break the binary apart into different pieces. So using chars is the easiest way I think.

I'm new to C so bear with me. The user has to enter a hex number and then it gets passed to my function. I use if / else to get the binary for each char in the char array. So if user enters 30 , then I want to return the array of chars like "00110000", but I'm getting the Segmentation fault error.

Does anyone know why and how I can fix this? Also I am getting warning that says passing argument 1 pf strcopy makes pointer from integer without a cast?

char *hextobin(char *hex, int m);
int main(int argc, char **argv) {

  int m = 8;
  char *address;
  printf("Enter an hex: ");
  scanf("%s", address);

  address = hextobin(address, m);

  return 0;
}

/*convert hexadecimal to binary*/
char *hextobin(char *hex, int m) {
  char p[m - 1];
  int i = 0;
  while (hex[i] != '/0') {
    if (hex[i] == '0') {
      strcpy(p[i], "0000");
    } else if (hex[i] == '1') {
      strcpy(p[i], "0001");
    } else if (hex[i] == '2') {
      strcpy(p[i], "0010");
    } else if (hex[i] == '3') {
      strcpy(p[i], "0011");
    } else if (hex[i] == '4') {
      strcpy(p[i], "0100");
    } else if (hex[i] == '5') {
      strcpy(p[i], "0101");
    } else if (hex[i] == '6') {
      strcpy(p[i], "0110");
    } else if (hex[i] == '7') {
      strcpy(p[i], "0111");
    } else if (hex[i] == '8') {
      strcpy(p[i], "1000");
    } else if (hex[i] == '9') {
      strcpy(p[i], "1001");
    } else if (hex[i] == 'a') {
      strcpy(p[i], "1010");
    } else if (hex[i] == 'b') {
      strcpy(p[i], "1011");
    } else if (hex[i] == 'c') {
      strcpy(p[i], "1100");
    } else if (hex[i] == 'd') {
      strcpy(p[i], "1101");
    } else if (hex[i] == 'e') {
      strcpy(p[i], "1110");
    } else if (hex[i] == 'f') {
      strcpy(p[i], "1111");
    } else
      printf("Invalid Hex!!\n");

    i++;
  }
  return p;
}

address is an uninitialized pointer, you must make it point to a valid memory address that can contain the string passed to it by scanf .

You need either to allocate memory to it, or declare it as a char array with the needed size.

This is likely the reason why you have a segmentation fault. There are, however, other issues in the code like the fact that you are returning a pointer to a local variable that will go out of scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM