Мартин Бее Мартин Бее - 3 months ago 20
C Question

Memory access violation using malloc()

Why this code cause memory violation?

void vLogInfo(char *);
unsigned short usGetPhase();

void vCheck()
{
unsigned short usTmp = usGetPhase();
char *cTmp = malloc(sizeof(char) * 250);
sprintf(cTmp, usTmp);
vLogInfo(cTmp);
free(cTmp);
}

Answer

You are misusing sprintf. It's typical usage is something like this:

 char buffer [50];
 sprintf (buffer, "%d plus %d is %d", 5, 4, 9 );
 printf("%s", buffer);
Comments