Frage

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.
War es hilfreich?

Lösung

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.

Andere Tipps

While itoa() is defined as taking a pointer argument, that pointer must point to a memory block suficiently large to accept the result. In your case the pointers are unitialised.

The simplest solution is to declare suitably sized arrays. Arrays can be passed to functions accepting pointer arguments - they are passed by reference, so the function receives a pointer to the array, not a copy of it.

char sValue[22] ;
char sFreq[22] ;

The size of the array is sufficient to accept a 64 bit integer with a potential sign prefix. It need be only 12 for 32 bit, but you may as well ensure you don't have to know what the code will be compiled for.

An alternative to itoa would be to use sprintf:

sprintf( sValue, "%u", i ) ;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top