I'd like to use calloc and snprintf. Can you review my simple code and tell me how to fix it? I kept having an error that Access violation writing location 0xFFFFFFFFB8A2D1F0. Thank you!
int main()
{
char* buffer1;
buffer1 = (char*)calloc(1, 14);
int a = 15;
int b = 25;
char c[]="MON"
int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);
return 0;
}
Hopefully please fix this simple code.
This works for me:
#include <stdio.h>
#include <stdlib.h> // <string.h> not needed
int main(void)
{
char* buffer1;
buffer1 = calloc(1, 14); // cast not needed
if (!buffer1) { fprintf(stderr, "Memory Failure.\n"); exit(EXIT_FAILURE); }
int a = 15;
int b = 25;
char c[4] = "MON";
int k = snprintf(buffer1, 13, "%02d%02d%s", a, b, c);
// --------------- ^ ---------------
printf("k is %d; buffer1 has [%s]\n", k, buffer1);
free(buffer1); // release resources no longer needed
return 0;
}