Search code examples
ccodeblocksitoa

itoa in C using Codeblocks causes segmentation error


Been playing with itoa() for a school project and it was working fine then started to throw errors. Says its having a segmenation error when first instance of itoa is handled.

Here's the offending code.

I don't see why it would work at first then start having issues. The only thing I had added pre-breakdown was some lines of printf() at the bottom which I didn't include as I've already commented them out of the code and it still doesn't work.

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

int main()
{

//Variables

unsigned int byteH=0b00011001;
unsigned int byteL=0b00001110;
char* sValue;
char* sFreq;
float iConv;
char Output[4];
int i;


i=((byteH*32)+byteL);  // just adding two 5bit blocks together

itoa(i,sValue,10);     // This instance throws the segmenation error

iConv=((byteH*32)+byteL);
iConv=(int)(iConv/1.023);
i=(int)iConv;

itoa(i,sFreq,10);     // This instance doesn't cause problems.

Solution

  • The function itoa expects an alreay allocated buffer. Try:

    char* sValue = malloc(20);
    

    Same goes for sFreq, even if it happens to "work" as it is.