strncpy overwrites existing character string

stan picture stan · Sep 10, 2011 · Viewed 8.7k times · Source

I've created a function to convert a number into a roman numeral. I know the logic of the conversion itself is correct, however, each time strncpy is called, it overwrites the previous value of "rom". I even tried calling it back to back and it only returned the latter.

Here's a snippet from the code:

   char* rom = (char*) calloc (10,sizeof(char));

    while(intval>=1000){
        intval -= 1000;
    strncpy(rom,"M",2);
    }

Maybe using calloc is part of the issue, but I tried using malloc and it gave me the same result.

Answer

Foo Bah picture Foo Bah · Sep 10, 2011

you want to append, but strcpy just copies to the address (and overwrites). use strcat or strncat