Beer Song: Not able to identify the Bug

,
#include "beer_song.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

void recite(uint8_t start_bottles, uint8_t take_down, char **song)
{
    
    while(take_down > 0) 
    {        
        if(start_bottles == 0) 
        {
            sprintf(*song++, "No more bottles of beer on the wall, no more bottles of beer.");
            sprintf(*song++, "Go to the store and buy some more, 99 bottles of beer on the wall.");
            break;
        }

        sprintf(*song++, "%d bottle%s of beer on the wall, %d bottle%s of beer.", start_bottles, (start_bottles == 1 ? "" : "s"), start_bottles, (start_bottles == 1 ? "" : "s"));

        start_bottles--;

        if (start_bottles > 0) {
            sprintf(*song++, "Take one down and pass it around, %d bottle%s of beer on the wall.",
                               start_bottles, (start_bottles == 1 ? "" : "s"));
        } else {
            sprintf(*song++, "Take it down and pass it around, no more bottles of beer on the wall.");
        }

        take_down--;
     }
}

Please provide hint to identify what is missing.

Identified the bug, testcase included “” in the middle.

One of the Testcases

static void test_last_three_verses(void)
{
   TEST_IGNORE();
   uint16_t expected_line_count = 8;
   const char expected_song[][MAX_LINE_LENGTH] = {
      "2 bottles of beer on the wall, 2 bottles of beer.",
      "Take one down and pass it around, 1 bottle of beer on the wall.",
      "",
      "1 bottle of beer on the wall, 1 bottle of beer.",
      "Take it down and pass it around, no more bottles of beer on the wall.",
      "",
      "No more bottles of beer on the wall, no more bottles of beer.",
      "Go to the store and buy some more, 99 bottles of beer on the wall."
   };
   recite(2, 3, actual_song);
   check_song(expected_line_count, expected_song, actual_song);
} 

Now, getting this error :
We received the following error when we ran your code:

./beer_song.c: In function 'recite':
./beer_song.c:29:26: error: zero-length gnu_printf format string [-Werror=format-zero-length]
   29 |         sprintf(*song++, "");
      |                          ^~
cc1: all warnings being treated as errors
make: *** [makefile:37: tests.out] Error 1

@Naavin The error message from the compiler indicates that "" cannot be used as a format string. In general, sprintf should only be used to format values. For example,

sprintf(s, "The answer is %d", 42)

For cases where you just want to copy one string into another, a better choice is strcpy.

Thanks for sharing. Problem solved.

1 Like