954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Switching from Java to C for a class, getting segfault, don't know why.

I wrote this small program for a class im taking, and its supposed to take an int n and a radix (int between 2 and 16) r and give me the number converted to the new base. It only has to go from decimal to other radix's. I run my program and put in the input but for some reason im getting a segmentation fault. I know this means I most likely have a memory allocation issue but i don't know where, why, or how to find it. Can someone please show me where I went wrong?

/*Adam Ross Cohen -- 000891451 -- CSI333 Fall 09 Program 1a*/
#include <stdio.h>

int main(void)
{
  int n, r, i, count, temp;
  count = 0;
  char hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  char ans[40];
  printf("Enter two integers (the ladder between 2 and 16): ");
  scanf("%d",&n);
  printf("you entered %d \n",n);
  scanf("%d",&r);
  printf("You entered %d \n",r);
  temp = n;
  while(n != 0)
    {
      temp = n % r;
      ans[count] = hex[temp];
      count++;
    }
  for(i = 39; i > 0; i--)
    {
      printf("%c", ans[i]);
    }
  return 0;
}


thanks ahead of time for any help.

splurchner
Newbie Poster
8 posts since May 2009
Reputation Points: 10
Solved Threads: 0
 

pls reconsider your while loop. its a infinite loop. 'n' never changes so 'count' gets continuous increment. hence 'ans[count]' gives segfault.

codeguru_2009
Light Poster
31 posts since Aug 2009
Reputation Points: 46
Solved Threads: 6
 

thanks, that was really foolish of me, probably would have never noticed it on my own though.

splurchner
Newbie Poster
8 posts since May 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: