1

I was trying to write a program to convert numbers into Roman Numerals. (It is a duplicate of the code found here: How to convert integer value to Roman numeral string? ) I am pretty sure the program logic is al-right. Here is my code:

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

int main(){
const char *huns[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
const char *tens[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
const char *ones[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
const int size[] = {0, 1, 2, 3, 2, 1, 2, 3, 4, 2};

char *_buffer;
unsigned int num;

input:
printf("Enter number to convert:\n");
scanf("%ud", &num);

if(num>4000)
    goto input;

while(num>=1000){
    *_buffer++ = 'M';
    num -= 1000;
}

strcpy (_buffer, huns[num/100]); _buffer += size[num/100]; num = num % 100;
strcpy (_buffer, tens[num/10]);  _buffer += size[num/10];  num = num % 10;
strcpy (_buffer, ones[num]);     _buffer += size[num];

*_buffer ='\0';
printf("%s", _buffer); // This is where the Runtime Error occurs.

return 0;
}

Can someone please explain why printf() causes a runtime error here? I tried puts() as well and it didn't work. I've tried compiling and running in Code:Blocks 13.11 (MINGW gcc) as well as http://ideone.com , but both give the same error.

Community
  • 1
  • 1
Quirk
  • 1,305
  • 4
  • 15
  • 29

1 Answers1

0

you problem is (and the compiler has probably already issued a warning about this) _buffer is uninitialized, meaning that it is pointing to some random address in memory - hence your runtime error. Change your code to

char buffer [128];
char *_buffer=buffer;

and printf buffer (not _buffer).

Anonymouse
  • 935
  • 9
  • 20
  • The compiler did not show any warning.(That is what irked me off). Thanks for the fix though. I believe I did not pre-assign memory for the buffer and hence this problem. – Quirk Apr 27 '14 at 10:43
  • a good compiler would have warned about using an uninitialized variable. Try turning the warning level up (gnu-c: `-Wall`) – Anonymouse Apr 27 '14 at 12:31