geek
geek

Reputation: 11

How to use calloc and snprintf

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.

Upvotes: 0

Views: 115

Answers (2)

pmg
pmg

Reputation: 108988

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;
}

See https://ideone.com/WMtMQt

Upvotes: 2

ikegami
ikegami

Reputation: 386541

The code you posted doesn't compile.

source>:21:5: error: expected ',' or ';' before 'int'
   21 |     int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);
      |     ^~~

Let's fixed that.

Still, the fixed code has numerous warnings.

<source>: In function 'main':
<source>:21:42: warning: conversion lacks type at end of format [-Wformat=]
   21 |     int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);
      |                                          ^
<source>:21:44: warning: format '%s' expects argument of type 'char *', but argument 5 has type 'int' [-Wformat=]
   21 |     int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);
      |                                           ~^      ~
      |                                            |      |
      |                                            char * int
      |                                           %d
<source>:21:35: warning: too many arguments for format [-Wformat-extra-args]
   21 |     int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);
      |                                   ^~~~~~~~~~~
<source>:21:9: warning: unused variable 'k' [-Wunused-variable]
   21 |     int k = snprintf(buffer1, 13, "%02d%02%s", a, b, c);

The issue is the missing d in the format string.

ALWAYS enable your compiler's warnings and hede them. With gcc, you could use -Wall -Wextra -pedantic -Werror.

Upvotes: 1

Related Questions