Home > database >  snprintf function keeps pausing and cause the program to terminate in C
snprintf function keeps pausing and cause the program to terminate in C

Time:07-12

I have been working on this function that takes a customer struct and returns an allocated string with detailed info using snprintf to form the string.

char* to_string(custumer cus)
{
    char* buffer = (char*) malloc(BUFFER_SIZE);
    snprintf(buffer, BUFFER_SIZE, "||%-30s||-/-/M||%-30s||%-10s||-/-/%-4d||%-10.4lf||%-16s||"
    , cus.name, cus.birth.date, cus.birth.month, cus.birth.year, cus.address, cus.phone, 
    cus.opening.date, cus.opening.month, cus.opening.year, cus.opening, cus.balance, cus.cardnum);
    return buffer;
}

Detailed structs and macros:

#define FONE_SIZE 10
#define CARD_SIZE 16
#define NAME_SIZE 50
#define ADDRESS_SIZE 100
#define MAXCUS_SIZE 300
#define CHOICE_SIZE 18
#define BUFFER_SIZE 255

typedef struct {
    int date;
    int month;
    int year;
} date;

typedef struct {

    char name[NAME_SIZE];
    date birth;
    char address[ADDRESS_SIZE];
    char phone[FONE_SIZE];
    date opening;
    double balance;
    char cardnum[CARD_SIZE];

} custumer;

I'm implementing the function like this:

void print_cus(custumer* cus_arr, int cus_num)
{
    printf("||%-30s||%-10s||%-30s||%-10s||%-10s||%-10s||%-16s||\n", "Custumer's name", "Birth day", "Custumer's adress", "Phone number", "Open date", "Balance", "Card number");

    for(int i = 0; i < cus_num; i  )
    {
        char* buffer = to_string(cus_arr[i]);
        puts(buffer);
        free(buffer);
    }
}

Then, when I run the program on Windows, it pauses and terminates. I used VS Code's debugger and noticed that the bug happened when the snprintf function was called. I completely don't know the reason for it and any help would be awesome. The debugger shows errors like this:

enter image description here

CodePudding user response:

You pass 12 data arguments to your snprint call but provide only 11 format specifiers.

It would seem to me that the cus.opening argument is superfluous – indeed, how does snprint know what to do with that structure argument?

Compiling your code as provided, clang-cl gives three warnings for that snprintf call:

warning : format specifies type 'double' but the argument has type 'date' [-Wformat]
warning : format specifies type 'char *' but the argument has type 'double' [-Wformat]
warning : data argument not used by format string [-Wformat-extra-args]

Removing the cus.opening argument from the call removes all three warnings.

Also, as mentioned in the comments, you should always check that a call to malloc has succeeded and include error-handling code should it fail (i.e. returns NULL). And please read: Do I cast the result of malloc?

  • Related