Mark
Mark

Reputation: 8688

What is wrong with my c code?

I am getting segmentation fault for the code below. To compile I typed gcc -std=c99 -g alphacode.c. This is a problem I am solving from here, and I am not sure what the problem is.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int catchar(char a, char b) {

  char a1[2];
  a1[1] = a;
  a1[0] = b;

  return atoi(a1);
}

int processNumber(char *num) {
 int size = strlen(num);
 int p[size];

 if (num[size-1] != 0)
   p[size-1] = 1;
 else
   p[size-1] = 0;

 int i;
 for (i = size-2; i>=0; i--)
    {

      if (catchar(num[i], num[i-1]) > 26 ||
      catchar(num[i] , num[i-1]) <1 || num[i] == 0) 
    p[i] = p[i-1];    
      else
    p[i] = p[i-1] + p[i-2];

    }

 return p[0];

}


int main() {

    int bytes_read;
    int nbytes = 5000;
    char *number;
    bytes_read = getline (&number, &nbytes, stdin);
    while (bytes_read != -1) {

      int out = processNumber(number);
      printf("%d\n", out);
      bytes_read = getline (&number, &nbytes, stdin);

    }
    return 0;
}

Upvotes: 0

Views: 1850

Answers (2)

Tomas Pruzina
Tomas Pruzina

Reputation: 8887

String needs to be null(0) terminated, thus you need array of 3 ( [a][b][\0]).

int catchar(char a, char b) 
{
  char concat[3] = { a,b,NULL};

  return atoi(concat);
}

Upvotes: 0

amit
amit

Reputation: 178511

int catchar(char a, char b) {

  char a1[2];
  a1[1] = a;
  a1[0] = b;

  return atoi(a1);
}

atoi() expects a string, and a string must have a '\0' terminator, without it - atoi() will just keep looking until it find '\0', and you might get garbage or segfault - if you are out of your allocated memory.

You should declare your array of size 3, and put '\0' at index 2.

Upvotes: 4

Related Questions