Program that generates brainfuck code that outputs given text The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Optimizing string replacement program that uses recursionClassifying lexemes in a given C programInterpreting Brainfuck code to C#, then compiling to a .exeC program that reverses a stringBrainfuck code optimization in PythonC program that recovers lost JPEG filesProgram to find megaPrime numbers between 2 given integersDice roll game that generates random numberProgram that prints out the initials of a given nameText to Brainfuck translator

Hiding Certain Lines on Table

how can a perfect fourth interval be considered either consonant or dissonant?

What is this lever in Argentinian toilets?

Windows 10: How to Lock (not sleep) laptop on lid close?

What can I do if neighbor is blocking my solar panels intentionally?

How are presidential pardons supposed to be used?

rotate text in posterbox

Is above average number of years spent on PhD considered a red flag in future academia or industry positions?

How is simplicity better than precision and clarity in prose?

How can I define good in a religion that claims no moral authority?

How to split app screen on my Mac?

The variadic template constructor of my class cannot modify my class members, why is that so?

Road tyres vs "Street" tyres for charity ride on MTB Tandem

Slither Like a Snake

Why can't wing-mounted spoilers be used to steepen approaches?

Why does the Event Horizon Telescope (EHT) not include telescopes from Africa, Asia or Australia?

Python - Fishing Simulator

How to delete random line from file using Unix command?

Semisimplicity of the category of coherent sheaves?

Would an alien lifeform be able to achieve space travel if lacking in vision?

Movie about afterlife I think? Large towers with clothing and food?

Can withdrawing asylum be illegal?

Wall plug outlet change

What do you call a plan that's an alternative plan in case your initial plan fails?



Program that generates brainfuck code that outputs given text



The 2019 Stack Overflow Developer Survey Results Are In
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Optimizing string replacement program that uses recursionClassifying lexemes in a given C programInterpreting Brainfuck code to C#, then compiling to a .exeC program that reverses a stringBrainfuck code optimization in PythonC program that recovers lost JPEG filesProgram to find megaPrime numbers between 2 given integersDice roll game that generates random numberProgram that prints out the initials of a given nameText to Brainfuck translator



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








5












$begingroup$


I created program that generates brainfuck code that outputs given text.
Arguments for the program are input file with the text and output file where code will be generated to.
Here is the code:



#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ALLOCATION_ERROR 1
#define FILE_ERROR 2
#define OTHER_ERROR 3

static inline FILE*
get_file_pointer(const char* filename,const char* mode)
FILE* file_pointer=fopen(filename,mode);
if(file_pointer==NULL)
fprintf(stderr,"Error: failed to open file %sn",filename);
exit(FILE_ERROR);

return file_pointer;

static inline char*
int_to_brainfuck(int difference)
if(difference==0)
return ".";
else
char character_in_loop=difference>0?'+':'-';
difference=difference>0?difference:-difference;
const unsigned int loop_body_length=17;
const unsigned int number_of_ones=(unsigned int)(difference%10);
const unsigned int number_of_tens=(unsigned int)(difference/10);
char* brainfuck_code=calloc(number_of_tens+loop_body_length+number_of_ones+2,sizeof*brainfuck_code);
if(number_of_tens>0)
brainfuck_code[strlen(brainfuck_code)]='>';
memset(brainfuck_code+strlen(brainfuck_code),'+',number_of_tens);
strcat(brainfuck_code+strlen(brainfuck_code),"[<");
memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,10);
strcat(brainfuck_code+strlen(brainfuck_code),">-]<");

memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,number_of_ones);
brainfuck_code[strlen(brainfuck_code)]='.';
return brainfuck_code;


static inline void
generate_code(FILE* input_file,FILE* output_file)
int current_char,last_char=0;
while((current_char=fgetc(input_file))!=EOF)
char* brainfuck_code=int_to_brainfuck(current_char-last_char);
fputs(brainfuck_code,output_file);
if(brainfuck_code[0]!='.')
free(brainfuck_code);
last_char=current_char;


static inline void
parse_args(int argc)
if(argc!=3)
puts("Usage: bfgen <input> <output>");
exit(OTHER_ERROR);


int
main(int argc,char** argv)
parse_args(argc);
FILE* input_file=get_file_pointer(argv[1],"r");
FILE* output_file=get_file_pointer(argv[2],"wb");
generate_code(input_file,output_file);
fclose(input_file);
fclose(output_file);
return 0;










share|improve this question











$endgroup$


















    5












    $begingroup$


    I created program that generates brainfuck code that outputs given text.
    Arguments for the program are input file with the text and output file where code will be generated to.
    Here is the code:



    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    #define ALLOCATION_ERROR 1
    #define FILE_ERROR 2
    #define OTHER_ERROR 3

    static inline FILE*
    get_file_pointer(const char* filename,const char* mode)
    FILE* file_pointer=fopen(filename,mode);
    if(file_pointer==NULL)
    fprintf(stderr,"Error: failed to open file %sn",filename);
    exit(FILE_ERROR);

    return file_pointer;

    static inline char*
    int_to_brainfuck(int difference)
    if(difference==0)
    return ".";
    else
    char character_in_loop=difference>0?'+':'-';
    difference=difference>0?difference:-difference;
    const unsigned int loop_body_length=17;
    const unsigned int number_of_ones=(unsigned int)(difference%10);
    const unsigned int number_of_tens=(unsigned int)(difference/10);
    char* brainfuck_code=calloc(number_of_tens+loop_body_length+number_of_ones+2,sizeof*brainfuck_code);
    if(number_of_tens>0)
    brainfuck_code[strlen(brainfuck_code)]='>';
    memset(brainfuck_code+strlen(brainfuck_code),'+',number_of_tens);
    strcat(brainfuck_code+strlen(brainfuck_code),"[<");
    memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,10);
    strcat(brainfuck_code+strlen(brainfuck_code),">-]<");

    memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,number_of_ones);
    brainfuck_code[strlen(brainfuck_code)]='.';
    return brainfuck_code;


    static inline void
    generate_code(FILE* input_file,FILE* output_file)
    int current_char,last_char=0;
    while((current_char=fgetc(input_file))!=EOF)
    char* brainfuck_code=int_to_brainfuck(current_char-last_char);
    fputs(brainfuck_code,output_file);
    if(brainfuck_code[0]!='.')
    free(brainfuck_code);
    last_char=current_char;


    static inline void
    parse_args(int argc)
    if(argc!=3)
    puts("Usage: bfgen <input> <output>");
    exit(OTHER_ERROR);


    int
    main(int argc,char** argv)
    parse_args(argc);
    FILE* input_file=get_file_pointer(argv[1],"r");
    FILE* output_file=get_file_pointer(argv[2],"wb");
    generate_code(input_file,output_file);
    fclose(input_file);
    fclose(output_file);
    return 0;










    share|improve this question











    $endgroup$














      5












      5








      5





      $begingroup$


      I created program that generates brainfuck code that outputs given text.
      Arguments for the program are input file with the text and output file where code will be generated to.
      Here is the code:



      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>

      #define ALLOCATION_ERROR 1
      #define FILE_ERROR 2
      #define OTHER_ERROR 3

      static inline FILE*
      get_file_pointer(const char* filename,const char* mode)
      FILE* file_pointer=fopen(filename,mode);
      if(file_pointer==NULL)
      fprintf(stderr,"Error: failed to open file %sn",filename);
      exit(FILE_ERROR);

      return file_pointer;

      static inline char*
      int_to_brainfuck(int difference)
      if(difference==0)
      return ".";
      else
      char character_in_loop=difference>0?'+':'-';
      difference=difference>0?difference:-difference;
      const unsigned int loop_body_length=17;
      const unsigned int number_of_ones=(unsigned int)(difference%10);
      const unsigned int number_of_tens=(unsigned int)(difference/10);
      char* brainfuck_code=calloc(number_of_tens+loop_body_length+number_of_ones+2,sizeof*brainfuck_code);
      if(number_of_tens>0)
      brainfuck_code[strlen(brainfuck_code)]='>';
      memset(brainfuck_code+strlen(brainfuck_code),'+',number_of_tens);
      strcat(brainfuck_code+strlen(brainfuck_code),"[<");
      memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,10);
      strcat(brainfuck_code+strlen(brainfuck_code),">-]<");

      memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,number_of_ones);
      brainfuck_code[strlen(brainfuck_code)]='.';
      return brainfuck_code;


      static inline void
      generate_code(FILE* input_file,FILE* output_file)
      int current_char,last_char=0;
      while((current_char=fgetc(input_file))!=EOF)
      char* brainfuck_code=int_to_brainfuck(current_char-last_char);
      fputs(brainfuck_code,output_file);
      if(brainfuck_code[0]!='.')
      free(brainfuck_code);
      last_char=current_char;


      static inline void
      parse_args(int argc)
      if(argc!=3)
      puts("Usage: bfgen <input> <output>");
      exit(OTHER_ERROR);


      int
      main(int argc,char** argv)
      parse_args(argc);
      FILE* input_file=get_file_pointer(argv[1],"r");
      FILE* output_file=get_file_pointer(argv[2],"wb");
      generate_code(input_file,output_file);
      fclose(input_file);
      fclose(output_file);
      return 0;










      share|improve this question











      $endgroup$




      I created program that generates brainfuck code that outputs given text.
      Arguments for the program are input file with the text and output file where code will be generated to.
      Here is the code:



      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>

      #define ALLOCATION_ERROR 1
      #define FILE_ERROR 2
      #define OTHER_ERROR 3

      static inline FILE*
      get_file_pointer(const char* filename,const char* mode)
      FILE* file_pointer=fopen(filename,mode);
      if(file_pointer==NULL)
      fprintf(stderr,"Error: failed to open file %sn",filename);
      exit(FILE_ERROR);

      return file_pointer;

      static inline char*
      int_to_brainfuck(int difference)
      if(difference==0)
      return ".";
      else
      char character_in_loop=difference>0?'+':'-';
      difference=difference>0?difference:-difference;
      const unsigned int loop_body_length=17;
      const unsigned int number_of_ones=(unsigned int)(difference%10);
      const unsigned int number_of_tens=(unsigned int)(difference/10);
      char* brainfuck_code=calloc(number_of_tens+loop_body_length+number_of_ones+2,sizeof*brainfuck_code);
      if(number_of_tens>0)
      brainfuck_code[strlen(brainfuck_code)]='>';
      memset(brainfuck_code+strlen(brainfuck_code),'+',number_of_tens);
      strcat(brainfuck_code+strlen(brainfuck_code),"[<");
      memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,10);
      strcat(brainfuck_code+strlen(brainfuck_code),">-]<");

      memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,number_of_ones);
      brainfuck_code[strlen(brainfuck_code)]='.';
      return brainfuck_code;


      static inline void
      generate_code(FILE* input_file,FILE* output_file)
      int current_char,last_char=0;
      while((current_char=fgetc(input_file))!=EOF)
      char* brainfuck_code=int_to_brainfuck(current_char-last_char);
      fputs(brainfuck_code,output_file);
      if(brainfuck_code[0]!='.')
      free(brainfuck_code);
      last_char=current_char;


      static inline void
      parse_args(int argc)
      if(argc!=3)
      puts("Usage: bfgen <input> <output>");
      exit(OTHER_ERROR);


      int
      main(int argc,char** argv)
      parse_args(argc);
      FILE* input_file=get_file_pointer(argv[1],"r");
      FILE* output_file=get_file_pointer(argv[2],"wb");
      generate_code(input_file,output_file);
      fclose(input_file);
      fclose(output_file);
      return 0;







      c brainfuck compiler






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 hours ago









      200_success

      131k17157422




      131k17157422










      asked 4 hours ago









      DeBos99DeBos99

      1267




      1267




















          1 Answer
          1






          active

          oldest

          votes


















          2












          $begingroup$

          I opened your code in CLion. The first thing it marked was:



          #define ALLOCATION_ERROR 1


          It's unused.



          Other than that, there were no warnings, which is already quite good.



          Next I compiled your code using both GCC and CLang:



          $ gcc -Wall -Wextra -Os -c bfgen.c
          $ clang -Wall -Weverything -Os -c bfgen.c
          bfgen.c:5:9: warning: macro is not used [-Wunused-macros]
          #define ALLOCATION_ERROR 1
          ^
          1 warning generated.


          That's also good. You prepared your code quite well for this code review by fixing the compiler warnings (if there had been any).



          Now to the human part of the code review.



          I would remove the inline from the function definitions. Trust the compiler to do the right thing here.



          The word get in the function name get_file_pointer makes it sound as if this function had no side effects. This assumption is wrong. The function should have a better name. It is typical for these error-checking wrapper functions to be prefixed with x. You will find many implementations of xmalloc, xrealloc, xopen, and so on in other projects.



          In the get_file_pointer function, you should include the kind of error in the fprintf output:



          fprintf(stderr, "Error: failed to open file '%s': %sn", filename, strerror(errno));


          The function int_to_brainfuck has a bad name. It's clear from the function signature that it takes an int, therefore the function name should rather describe what that int means. It's a difference, but there is no documentation about what differs. After reading the whole code of the function I know that it's the difference between the previous character and the next character. This information should be encoded in the function name.



          Calling strlen repeatedly is a waste of time. At each point in the code you know exactly how long the string is, therefore it is more efficient to just store the current end of the brainfuck_code in a pointer and always strcpy to that pointer:



          size_t code_len = number_of_tens + loop_body_length + number_of_ones + 2;
          char *brainfuck_code = calloc(code_len, sizeof *brainfuck_code);
          char *code = brainfuck_code;

          if (number_of_tens > 0)
          *code++ = '>';
          memset(code, '+', number_of_tens);
          code += number_of_tens;
          strcpy(code, "[<");
          code += 3;
          memset(code, character_in_loop, 10);
          code += 10;
          strcpy(code, ">-]<");
          code += 4;


          memset(code, character_in_loop, number_of_ones);
          code += number_of_ones;
          *code++ = '.';

          assert(brainfuck_code + code_len == code);

          return brainfuck_code;


          I added the assert at the end because these explicit length calculations can always go wrong. If the compiler is smart enough, it will find out that this assertion always succeeds and may even eliminate it. And in case you forgot a character to change the code later, you will quickly get a crash dump instead of undefined behavior because of a buffer overflow.



          I suspected you had already calculated the length wrong because I couldn't find the first character in the formula. Instead, there's a magic number 2 in that formula. You should make the formula correspond to the actual code by writing it like this:



          size_t code_len = 1 + number_of_tens + 3 + 10 + 4 number_of_ones + 1;


          This allows you to quickly compare it to the code.



          Even better would be if you would not need this whole calculation at all. Since you are writing the output to a file anyway, you don't need to allocate the memory yourself. I'm thinking of two functions like these:



          typedef struct 
          FILE *out;
          bfgen;

          static void bfgen_emit_str(bfgen *gen, const char *code)
          ...


          static void bfgen_emit_repeat(bfgen *gen, char code, size_t n)
          ...



          Then you can simply write:



          static void
          bfgen_emit_difference(bfgen *gen, int difference)
          if (difference == 0)
          bfgen_emit_str(".");
          return;


          char character_in_loop = difference > 0 ? '+' : '-';
          unsigned int abs_diff = difference > 0 ? difference : -difference;
          unsigned int number_of_tens = abs_diff / 10;

          if (number_of_tens > 0)
          bfgen_emit_str(gen, ">");
          bfgen_emit_repeat(gen, '+', number_of_tens);
          bfgen_emit_str(gen, "[<");
          bfgen_emit_repeat(gen, character_in_loop, 10);
          bfgen_emit_str(gen, ">-]<");


          bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);
          bfgen_emit_str(gen, ".");



          This code looks much clearer. Now that you don't have to think about all this annoying buffer size calculation anymore, it becomes much easier to add new optimizations, such as avoiding the loop when number_of_tens is exactly 1. In the previous version of the code I wouldn't have added this feature out of laziness and fear of breaking things.



          Based on this example, you can see that the functions bfgen_emit_str and bfgen_emit_repeat are really useful, and implementing them is easy.



          static void bfgen_emit_str(bfgen *gen, const char *code) 
          fputs(code, gen->out);


          static void bfgen_emit_repeat(bfgen *gen, char code, size_t n)
          for (size_t i = 0; i < n; i++)
          fputc(code, gen->out);




          Looking at bfgen_emit_difference again, that function doesn't do what its name says. It doesn't only emit code to calculate the difference, it also emits code to print the resulting character. It shouldn't do that. The call to bfgen_emit_str(gen, ".") belongs in bfgen_generate_code instead.




          It doesn't matter anymore, but your original version of int_to_brainfuck was essentially:



          static char *
          int_to_brainfuck(...)
          if (condition)
          return ".";
          else
          return allocated_string;




          You must never write such a function since the caller cannot know whether they should free the string or not. This leads either to memory leaks or to undefined behavior. You don't want either of these.




          In the main function, you should open the input file in binary mode and the output file in text mode. Currently it's the other way round.




          The main takeaway from this code review is that it makes sense to define your own data structures and the corresponding functions. Make these functions as easy as possible to use. Free the caller from any unnecessary tasks such as calculating buffer sizes or managing memory, which are really boring and error-prone.



          An idea for further work is to make the generated code more efficient by keeping track of the actual memory contents. This can now be easily done in the struct bfgen. Then you can look which memory cell has currently the closest value and use that instead of just using a single memory cell.



          The rewritten and restructured code is:



          #include <errno.h>
          #include <stdio.h>
          #include <stdlib.h>
          #include <string.h>

          #define FILE_ERROR 2
          #define OTHER_ERROR 3

          static FILE *
          xopen(const char *filename, const char *mode)
          FILE *file_pointer = fopen(filename, mode);
          if (file_pointer == NULL)
          fprintf(stderr, "Error: failed to open file '%s': %sn",
          filename, strerror(errno));
          exit(FILE_ERROR);

          return file_pointer;


          typedef struct
          FILE *out;
          bfgen;

          static void
          bfgen_emit_str(bfgen *gen, const char *code)
          fputs(code, gen->out);


          static void
          bfgen_emit_repeat(bfgen *gen, char code, size_t n)
          for (size_t i = 0; i < n; i++)
          fputc(code, gen->out);



          static void
          bfgen_emit_difference(bfgen *gen, int difference)
          if (difference == 0)
          return;


          char character_in_loop = difference > 0 ? '+' : '-';
          unsigned int abs_diff = difference > 0 ? difference : -difference;
          unsigned int number_of_tens = abs_diff / 10;

          if (number_of_tens > 0)
          bfgen_emit_str(gen, ">");
          bfgen_emit_repeat(gen, '+', number_of_tens);
          bfgen_emit_str(gen, "[<");
          bfgen_emit_repeat(gen, character_in_loop, 10);
          bfgen_emit_str(gen, ">-]<");


          bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);


          static void
          bfgen_generate_code(bfgen *gen, FILE *input_file)
          int current_char, last_char = 0;
          while ((current_char = fgetc(input_file)) != EOF)
          bfgen_emit_difference(gen, current_char - last_char);
          bfgen_emit_str(gen, ".n");
          last_char = current_char;



          static void
          parse_args(int argc)
          if (argc != 3)
          puts("Usage: bfgen <input> <output>");
          exit(OTHER_ERROR);



          int
          main(int argc, char **argv)
          parse_args(argc);
          FILE *input_file = xopen(argv[1], "rb");
          FILE *output_file = xopen(argv[2], "w");
          bfgen gen = output_file;
          bfgen_generate_code(&gen, input_file);
          fclose(output_file);
          fclose(input_file);
          return 0;






          share|improve this answer











          $endgroup$













            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "196"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217422%2fprogram-that-generates-brainfuck-code-that-outputs-given-text%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2












            $begingroup$

            I opened your code in CLion. The first thing it marked was:



            #define ALLOCATION_ERROR 1


            It's unused.



            Other than that, there were no warnings, which is already quite good.



            Next I compiled your code using both GCC and CLang:



            $ gcc -Wall -Wextra -Os -c bfgen.c
            $ clang -Wall -Weverything -Os -c bfgen.c
            bfgen.c:5:9: warning: macro is not used [-Wunused-macros]
            #define ALLOCATION_ERROR 1
            ^
            1 warning generated.


            That's also good. You prepared your code quite well for this code review by fixing the compiler warnings (if there had been any).



            Now to the human part of the code review.



            I would remove the inline from the function definitions. Trust the compiler to do the right thing here.



            The word get in the function name get_file_pointer makes it sound as if this function had no side effects. This assumption is wrong. The function should have a better name. It is typical for these error-checking wrapper functions to be prefixed with x. You will find many implementations of xmalloc, xrealloc, xopen, and so on in other projects.



            In the get_file_pointer function, you should include the kind of error in the fprintf output:



            fprintf(stderr, "Error: failed to open file '%s': %sn", filename, strerror(errno));


            The function int_to_brainfuck has a bad name. It's clear from the function signature that it takes an int, therefore the function name should rather describe what that int means. It's a difference, but there is no documentation about what differs. After reading the whole code of the function I know that it's the difference between the previous character and the next character. This information should be encoded in the function name.



            Calling strlen repeatedly is a waste of time. At each point in the code you know exactly how long the string is, therefore it is more efficient to just store the current end of the brainfuck_code in a pointer and always strcpy to that pointer:



            size_t code_len = number_of_tens + loop_body_length + number_of_ones + 2;
            char *brainfuck_code = calloc(code_len, sizeof *brainfuck_code);
            char *code = brainfuck_code;

            if (number_of_tens > 0)
            *code++ = '>';
            memset(code, '+', number_of_tens);
            code += number_of_tens;
            strcpy(code, "[<");
            code += 3;
            memset(code, character_in_loop, 10);
            code += 10;
            strcpy(code, ">-]<");
            code += 4;


            memset(code, character_in_loop, number_of_ones);
            code += number_of_ones;
            *code++ = '.';

            assert(brainfuck_code + code_len == code);

            return brainfuck_code;


            I added the assert at the end because these explicit length calculations can always go wrong. If the compiler is smart enough, it will find out that this assertion always succeeds and may even eliminate it. And in case you forgot a character to change the code later, you will quickly get a crash dump instead of undefined behavior because of a buffer overflow.



            I suspected you had already calculated the length wrong because I couldn't find the first character in the formula. Instead, there's a magic number 2 in that formula. You should make the formula correspond to the actual code by writing it like this:



            size_t code_len = 1 + number_of_tens + 3 + 10 + 4 number_of_ones + 1;


            This allows you to quickly compare it to the code.



            Even better would be if you would not need this whole calculation at all. Since you are writing the output to a file anyway, you don't need to allocate the memory yourself. I'm thinking of two functions like these:



            typedef struct 
            FILE *out;
            bfgen;

            static void bfgen_emit_str(bfgen *gen, const char *code)
            ...


            static void bfgen_emit_repeat(bfgen *gen, char code, size_t n)
            ...



            Then you can simply write:



            static void
            bfgen_emit_difference(bfgen *gen, int difference)
            if (difference == 0)
            bfgen_emit_str(".");
            return;


            char character_in_loop = difference > 0 ? '+' : '-';
            unsigned int abs_diff = difference > 0 ? difference : -difference;
            unsigned int number_of_tens = abs_diff / 10;

            if (number_of_tens > 0)
            bfgen_emit_str(gen, ">");
            bfgen_emit_repeat(gen, '+', number_of_tens);
            bfgen_emit_str(gen, "[<");
            bfgen_emit_repeat(gen, character_in_loop, 10);
            bfgen_emit_str(gen, ">-]<");


            bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);
            bfgen_emit_str(gen, ".");



            This code looks much clearer. Now that you don't have to think about all this annoying buffer size calculation anymore, it becomes much easier to add new optimizations, such as avoiding the loop when number_of_tens is exactly 1. In the previous version of the code I wouldn't have added this feature out of laziness and fear of breaking things.



            Based on this example, you can see that the functions bfgen_emit_str and bfgen_emit_repeat are really useful, and implementing them is easy.



            static void bfgen_emit_str(bfgen *gen, const char *code) 
            fputs(code, gen->out);


            static void bfgen_emit_repeat(bfgen *gen, char code, size_t n)
            for (size_t i = 0; i < n; i++)
            fputc(code, gen->out);




            Looking at bfgen_emit_difference again, that function doesn't do what its name says. It doesn't only emit code to calculate the difference, it also emits code to print the resulting character. It shouldn't do that. The call to bfgen_emit_str(gen, ".") belongs in bfgen_generate_code instead.




            It doesn't matter anymore, but your original version of int_to_brainfuck was essentially:



            static char *
            int_to_brainfuck(...)
            if (condition)
            return ".";
            else
            return allocated_string;




            You must never write such a function since the caller cannot know whether they should free the string or not. This leads either to memory leaks or to undefined behavior. You don't want either of these.




            In the main function, you should open the input file in binary mode and the output file in text mode. Currently it's the other way round.




            The main takeaway from this code review is that it makes sense to define your own data structures and the corresponding functions. Make these functions as easy as possible to use. Free the caller from any unnecessary tasks such as calculating buffer sizes or managing memory, which are really boring and error-prone.



            An idea for further work is to make the generated code more efficient by keeping track of the actual memory contents. This can now be easily done in the struct bfgen. Then you can look which memory cell has currently the closest value and use that instead of just using a single memory cell.



            The rewritten and restructured code is:



            #include <errno.h>
            #include <stdio.h>
            #include <stdlib.h>
            #include <string.h>

            #define FILE_ERROR 2
            #define OTHER_ERROR 3

            static FILE *
            xopen(const char *filename, const char *mode)
            FILE *file_pointer = fopen(filename, mode);
            if (file_pointer == NULL)
            fprintf(stderr, "Error: failed to open file '%s': %sn",
            filename, strerror(errno));
            exit(FILE_ERROR);

            return file_pointer;


            typedef struct
            FILE *out;
            bfgen;

            static void
            bfgen_emit_str(bfgen *gen, const char *code)
            fputs(code, gen->out);


            static void
            bfgen_emit_repeat(bfgen *gen, char code, size_t n)
            for (size_t i = 0; i < n; i++)
            fputc(code, gen->out);



            static void
            bfgen_emit_difference(bfgen *gen, int difference)
            if (difference == 0)
            return;


            char character_in_loop = difference > 0 ? '+' : '-';
            unsigned int abs_diff = difference > 0 ? difference : -difference;
            unsigned int number_of_tens = abs_diff / 10;

            if (number_of_tens > 0)
            bfgen_emit_str(gen, ">");
            bfgen_emit_repeat(gen, '+', number_of_tens);
            bfgen_emit_str(gen, "[<");
            bfgen_emit_repeat(gen, character_in_loop, 10);
            bfgen_emit_str(gen, ">-]<");


            bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);


            static void
            bfgen_generate_code(bfgen *gen, FILE *input_file)
            int current_char, last_char = 0;
            while ((current_char = fgetc(input_file)) != EOF)
            bfgen_emit_difference(gen, current_char - last_char);
            bfgen_emit_str(gen, ".n");
            last_char = current_char;



            static void
            parse_args(int argc)
            if (argc != 3)
            puts("Usage: bfgen <input> <output>");
            exit(OTHER_ERROR);



            int
            main(int argc, char **argv)
            parse_args(argc);
            FILE *input_file = xopen(argv[1], "rb");
            FILE *output_file = xopen(argv[2], "w");
            bfgen gen = output_file;
            bfgen_generate_code(&gen, input_file);
            fclose(output_file);
            fclose(input_file);
            return 0;






            share|improve this answer











            $endgroup$

















              2












              $begingroup$

              I opened your code in CLion. The first thing it marked was:



              #define ALLOCATION_ERROR 1


              It's unused.



              Other than that, there were no warnings, which is already quite good.



              Next I compiled your code using both GCC and CLang:



              $ gcc -Wall -Wextra -Os -c bfgen.c
              $ clang -Wall -Weverything -Os -c bfgen.c
              bfgen.c:5:9: warning: macro is not used [-Wunused-macros]
              #define ALLOCATION_ERROR 1
              ^
              1 warning generated.


              That's also good. You prepared your code quite well for this code review by fixing the compiler warnings (if there had been any).



              Now to the human part of the code review.



              I would remove the inline from the function definitions. Trust the compiler to do the right thing here.



              The word get in the function name get_file_pointer makes it sound as if this function had no side effects. This assumption is wrong. The function should have a better name. It is typical for these error-checking wrapper functions to be prefixed with x. You will find many implementations of xmalloc, xrealloc, xopen, and so on in other projects.



              In the get_file_pointer function, you should include the kind of error in the fprintf output:



              fprintf(stderr, "Error: failed to open file '%s': %sn", filename, strerror(errno));


              The function int_to_brainfuck has a bad name. It's clear from the function signature that it takes an int, therefore the function name should rather describe what that int means. It's a difference, but there is no documentation about what differs. After reading the whole code of the function I know that it's the difference between the previous character and the next character. This information should be encoded in the function name.



              Calling strlen repeatedly is a waste of time. At each point in the code you know exactly how long the string is, therefore it is more efficient to just store the current end of the brainfuck_code in a pointer and always strcpy to that pointer:



              size_t code_len = number_of_tens + loop_body_length + number_of_ones + 2;
              char *brainfuck_code = calloc(code_len, sizeof *brainfuck_code);
              char *code = brainfuck_code;

              if (number_of_tens > 0)
              *code++ = '>';
              memset(code, '+', number_of_tens);
              code += number_of_tens;
              strcpy(code, "[<");
              code += 3;
              memset(code, character_in_loop, 10);
              code += 10;
              strcpy(code, ">-]<");
              code += 4;


              memset(code, character_in_loop, number_of_ones);
              code += number_of_ones;
              *code++ = '.';

              assert(brainfuck_code + code_len == code);

              return brainfuck_code;


              I added the assert at the end because these explicit length calculations can always go wrong. If the compiler is smart enough, it will find out that this assertion always succeeds and may even eliminate it. And in case you forgot a character to change the code later, you will quickly get a crash dump instead of undefined behavior because of a buffer overflow.



              I suspected you had already calculated the length wrong because I couldn't find the first character in the formula. Instead, there's a magic number 2 in that formula. You should make the formula correspond to the actual code by writing it like this:



              size_t code_len = 1 + number_of_tens + 3 + 10 + 4 number_of_ones + 1;


              This allows you to quickly compare it to the code.



              Even better would be if you would not need this whole calculation at all. Since you are writing the output to a file anyway, you don't need to allocate the memory yourself. I'm thinking of two functions like these:



              typedef struct 
              FILE *out;
              bfgen;

              static void bfgen_emit_str(bfgen *gen, const char *code)
              ...


              static void bfgen_emit_repeat(bfgen *gen, char code, size_t n)
              ...



              Then you can simply write:



              static void
              bfgen_emit_difference(bfgen *gen, int difference)
              if (difference == 0)
              bfgen_emit_str(".");
              return;


              char character_in_loop = difference > 0 ? '+' : '-';
              unsigned int abs_diff = difference > 0 ? difference : -difference;
              unsigned int number_of_tens = abs_diff / 10;

              if (number_of_tens > 0)
              bfgen_emit_str(gen, ">");
              bfgen_emit_repeat(gen, '+', number_of_tens);
              bfgen_emit_str(gen, "[<");
              bfgen_emit_repeat(gen, character_in_loop, 10);
              bfgen_emit_str(gen, ">-]<");


              bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);
              bfgen_emit_str(gen, ".");



              This code looks much clearer. Now that you don't have to think about all this annoying buffer size calculation anymore, it becomes much easier to add new optimizations, such as avoiding the loop when number_of_tens is exactly 1. In the previous version of the code I wouldn't have added this feature out of laziness and fear of breaking things.



              Based on this example, you can see that the functions bfgen_emit_str and bfgen_emit_repeat are really useful, and implementing them is easy.



              static void bfgen_emit_str(bfgen *gen, const char *code) 
              fputs(code, gen->out);


              static void bfgen_emit_repeat(bfgen *gen, char code, size_t n)
              for (size_t i = 0; i < n; i++)
              fputc(code, gen->out);




              Looking at bfgen_emit_difference again, that function doesn't do what its name says. It doesn't only emit code to calculate the difference, it also emits code to print the resulting character. It shouldn't do that. The call to bfgen_emit_str(gen, ".") belongs in bfgen_generate_code instead.




              It doesn't matter anymore, but your original version of int_to_brainfuck was essentially:



              static char *
              int_to_brainfuck(...)
              if (condition)
              return ".";
              else
              return allocated_string;




              You must never write such a function since the caller cannot know whether they should free the string or not. This leads either to memory leaks or to undefined behavior. You don't want either of these.




              In the main function, you should open the input file in binary mode and the output file in text mode. Currently it's the other way round.




              The main takeaway from this code review is that it makes sense to define your own data structures and the corresponding functions. Make these functions as easy as possible to use. Free the caller from any unnecessary tasks such as calculating buffer sizes or managing memory, which are really boring and error-prone.



              An idea for further work is to make the generated code more efficient by keeping track of the actual memory contents. This can now be easily done in the struct bfgen. Then you can look which memory cell has currently the closest value and use that instead of just using a single memory cell.



              The rewritten and restructured code is:



              #include <errno.h>
              #include <stdio.h>
              #include <stdlib.h>
              #include <string.h>

              #define FILE_ERROR 2
              #define OTHER_ERROR 3

              static FILE *
              xopen(const char *filename, const char *mode)
              FILE *file_pointer = fopen(filename, mode);
              if (file_pointer == NULL)
              fprintf(stderr, "Error: failed to open file '%s': %sn",
              filename, strerror(errno));
              exit(FILE_ERROR);

              return file_pointer;


              typedef struct
              FILE *out;
              bfgen;

              static void
              bfgen_emit_str(bfgen *gen, const char *code)
              fputs(code, gen->out);


              static void
              bfgen_emit_repeat(bfgen *gen, char code, size_t n)
              for (size_t i = 0; i < n; i++)
              fputc(code, gen->out);



              static void
              bfgen_emit_difference(bfgen *gen, int difference)
              if (difference == 0)
              return;


              char character_in_loop = difference > 0 ? '+' : '-';
              unsigned int abs_diff = difference > 0 ? difference : -difference;
              unsigned int number_of_tens = abs_diff / 10;

              if (number_of_tens > 0)
              bfgen_emit_str(gen, ">");
              bfgen_emit_repeat(gen, '+', number_of_tens);
              bfgen_emit_str(gen, "[<");
              bfgen_emit_repeat(gen, character_in_loop, 10);
              bfgen_emit_str(gen, ">-]<");


              bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);


              static void
              bfgen_generate_code(bfgen *gen, FILE *input_file)
              int current_char, last_char = 0;
              while ((current_char = fgetc(input_file)) != EOF)
              bfgen_emit_difference(gen, current_char - last_char);
              bfgen_emit_str(gen, ".n");
              last_char = current_char;



              static void
              parse_args(int argc)
              if (argc != 3)
              puts("Usage: bfgen <input> <output>");
              exit(OTHER_ERROR);



              int
              main(int argc, char **argv)
              parse_args(argc);
              FILE *input_file = xopen(argv[1], "rb");
              FILE *output_file = xopen(argv[2], "w");
              bfgen gen = output_file;
              bfgen_generate_code(&gen, input_file);
              fclose(output_file);
              fclose(input_file);
              return 0;






              share|improve this answer











              $endgroup$















                2












                2








                2





                $begingroup$

                I opened your code in CLion. The first thing it marked was:



                #define ALLOCATION_ERROR 1


                It's unused.



                Other than that, there were no warnings, which is already quite good.



                Next I compiled your code using both GCC and CLang:



                $ gcc -Wall -Wextra -Os -c bfgen.c
                $ clang -Wall -Weverything -Os -c bfgen.c
                bfgen.c:5:9: warning: macro is not used [-Wunused-macros]
                #define ALLOCATION_ERROR 1
                ^
                1 warning generated.


                That's also good. You prepared your code quite well for this code review by fixing the compiler warnings (if there had been any).



                Now to the human part of the code review.



                I would remove the inline from the function definitions. Trust the compiler to do the right thing here.



                The word get in the function name get_file_pointer makes it sound as if this function had no side effects. This assumption is wrong. The function should have a better name. It is typical for these error-checking wrapper functions to be prefixed with x. You will find many implementations of xmalloc, xrealloc, xopen, and so on in other projects.



                In the get_file_pointer function, you should include the kind of error in the fprintf output:



                fprintf(stderr, "Error: failed to open file '%s': %sn", filename, strerror(errno));


                The function int_to_brainfuck has a bad name. It's clear from the function signature that it takes an int, therefore the function name should rather describe what that int means. It's a difference, but there is no documentation about what differs. After reading the whole code of the function I know that it's the difference between the previous character and the next character. This information should be encoded in the function name.



                Calling strlen repeatedly is a waste of time. At each point in the code you know exactly how long the string is, therefore it is more efficient to just store the current end of the brainfuck_code in a pointer and always strcpy to that pointer:



                size_t code_len = number_of_tens + loop_body_length + number_of_ones + 2;
                char *brainfuck_code = calloc(code_len, sizeof *brainfuck_code);
                char *code = brainfuck_code;

                if (number_of_tens > 0)
                *code++ = '>';
                memset(code, '+', number_of_tens);
                code += number_of_tens;
                strcpy(code, "[<");
                code += 3;
                memset(code, character_in_loop, 10);
                code += 10;
                strcpy(code, ">-]<");
                code += 4;


                memset(code, character_in_loop, number_of_ones);
                code += number_of_ones;
                *code++ = '.';

                assert(brainfuck_code + code_len == code);

                return brainfuck_code;


                I added the assert at the end because these explicit length calculations can always go wrong. If the compiler is smart enough, it will find out that this assertion always succeeds and may even eliminate it. And in case you forgot a character to change the code later, you will quickly get a crash dump instead of undefined behavior because of a buffer overflow.



                I suspected you had already calculated the length wrong because I couldn't find the first character in the formula. Instead, there's a magic number 2 in that formula. You should make the formula correspond to the actual code by writing it like this:



                size_t code_len = 1 + number_of_tens + 3 + 10 + 4 number_of_ones + 1;


                This allows you to quickly compare it to the code.



                Even better would be if you would not need this whole calculation at all. Since you are writing the output to a file anyway, you don't need to allocate the memory yourself. I'm thinking of two functions like these:



                typedef struct 
                FILE *out;
                bfgen;

                static void bfgen_emit_str(bfgen *gen, const char *code)
                ...


                static void bfgen_emit_repeat(bfgen *gen, char code, size_t n)
                ...



                Then you can simply write:



                static void
                bfgen_emit_difference(bfgen *gen, int difference)
                if (difference == 0)
                bfgen_emit_str(".");
                return;


                char character_in_loop = difference > 0 ? '+' : '-';
                unsigned int abs_diff = difference > 0 ? difference : -difference;
                unsigned int number_of_tens = abs_diff / 10;

                if (number_of_tens > 0)
                bfgen_emit_str(gen, ">");
                bfgen_emit_repeat(gen, '+', number_of_tens);
                bfgen_emit_str(gen, "[<");
                bfgen_emit_repeat(gen, character_in_loop, 10);
                bfgen_emit_str(gen, ">-]<");


                bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);
                bfgen_emit_str(gen, ".");



                This code looks much clearer. Now that you don't have to think about all this annoying buffer size calculation anymore, it becomes much easier to add new optimizations, such as avoiding the loop when number_of_tens is exactly 1. In the previous version of the code I wouldn't have added this feature out of laziness and fear of breaking things.



                Based on this example, you can see that the functions bfgen_emit_str and bfgen_emit_repeat are really useful, and implementing them is easy.



                static void bfgen_emit_str(bfgen *gen, const char *code) 
                fputs(code, gen->out);


                static void bfgen_emit_repeat(bfgen *gen, char code, size_t n)
                for (size_t i = 0; i < n; i++)
                fputc(code, gen->out);




                Looking at bfgen_emit_difference again, that function doesn't do what its name says. It doesn't only emit code to calculate the difference, it also emits code to print the resulting character. It shouldn't do that. The call to bfgen_emit_str(gen, ".") belongs in bfgen_generate_code instead.




                It doesn't matter anymore, but your original version of int_to_brainfuck was essentially:



                static char *
                int_to_brainfuck(...)
                if (condition)
                return ".";
                else
                return allocated_string;




                You must never write such a function since the caller cannot know whether they should free the string or not. This leads either to memory leaks or to undefined behavior. You don't want either of these.




                In the main function, you should open the input file in binary mode and the output file in text mode. Currently it's the other way round.




                The main takeaway from this code review is that it makes sense to define your own data structures and the corresponding functions. Make these functions as easy as possible to use. Free the caller from any unnecessary tasks such as calculating buffer sizes or managing memory, which are really boring and error-prone.



                An idea for further work is to make the generated code more efficient by keeping track of the actual memory contents. This can now be easily done in the struct bfgen. Then you can look which memory cell has currently the closest value and use that instead of just using a single memory cell.



                The rewritten and restructured code is:



                #include <errno.h>
                #include <stdio.h>
                #include <stdlib.h>
                #include <string.h>

                #define FILE_ERROR 2
                #define OTHER_ERROR 3

                static FILE *
                xopen(const char *filename, const char *mode)
                FILE *file_pointer = fopen(filename, mode);
                if (file_pointer == NULL)
                fprintf(stderr, "Error: failed to open file '%s': %sn",
                filename, strerror(errno));
                exit(FILE_ERROR);

                return file_pointer;


                typedef struct
                FILE *out;
                bfgen;

                static void
                bfgen_emit_str(bfgen *gen, const char *code)
                fputs(code, gen->out);


                static void
                bfgen_emit_repeat(bfgen *gen, char code, size_t n)
                for (size_t i = 0; i < n; i++)
                fputc(code, gen->out);



                static void
                bfgen_emit_difference(bfgen *gen, int difference)
                if (difference == 0)
                return;


                char character_in_loop = difference > 0 ? '+' : '-';
                unsigned int abs_diff = difference > 0 ? difference : -difference;
                unsigned int number_of_tens = abs_diff / 10;

                if (number_of_tens > 0)
                bfgen_emit_str(gen, ">");
                bfgen_emit_repeat(gen, '+', number_of_tens);
                bfgen_emit_str(gen, "[<");
                bfgen_emit_repeat(gen, character_in_loop, 10);
                bfgen_emit_str(gen, ">-]<");


                bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);


                static void
                bfgen_generate_code(bfgen *gen, FILE *input_file)
                int current_char, last_char = 0;
                while ((current_char = fgetc(input_file)) != EOF)
                bfgen_emit_difference(gen, current_char - last_char);
                bfgen_emit_str(gen, ".n");
                last_char = current_char;



                static void
                parse_args(int argc)
                if (argc != 3)
                puts("Usage: bfgen <input> <output>");
                exit(OTHER_ERROR);



                int
                main(int argc, char **argv)
                parse_args(argc);
                FILE *input_file = xopen(argv[1], "rb");
                FILE *output_file = xopen(argv[2], "w");
                bfgen gen = output_file;
                bfgen_generate_code(&gen, input_file);
                fclose(output_file);
                fclose(input_file);
                return 0;






                share|improve this answer











                $endgroup$



                I opened your code in CLion. The first thing it marked was:



                #define ALLOCATION_ERROR 1


                It's unused.



                Other than that, there were no warnings, which is already quite good.



                Next I compiled your code using both GCC and CLang:



                $ gcc -Wall -Wextra -Os -c bfgen.c
                $ clang -Wall -Weverything -Os -c bfgen.c
                bfgen.c:5:9: warning: macro is not used [-Wunused-macros]
                #define ALLOCATION_ERROR 1
                ^
                1 warning generated.


                That's also good. You prepared your code quite well for this code review by fixing the compiler warnings (if there had been any).



                Now to the human part of the code review.



                I would remove the inline from the function definitions. Trust the compiler to do the right thing here.



                The word get in the function name get_file_pointer makes it sound as if this function had no side effects. This assumption is wrong. The function should have a better name. It is typical for these error-checking wrapper functions to be prefixed with x. You will find many implementations of xmalloc, xrealloc, xopen, and so on in other projects.



                In the get_file_pointer function, you should include the kind of error in the fprintf output:



                fprintf(stderr, "Error: failed to open file '%s': %sn", filename, strerror(errno));


                The function int_to_brainfuck has a bad name. It's clear from the function signature that it takes an int, therefore the function name should rather describe what that int means. It's a difference, but there is no documentation about what differs. After reading the whole code of the function I know that it's the difference between the previous character and the next character. This information should be encoded in the function name.



                Calling strlen repeatedly is a waste of time. At each point in the code you know exactly how long the string is, therefore it is more efficient to just store the current end of the brainfuck_code in a pointer and always strcpy to that pointer:



                size_t code_len = number_of_tens + loop_body_length + number_of_ones + 2;
                char *brainfuck_code = calloc(code_len, sizeof *brainfuck_code);
                char *code = brainfuck_code;

                if (number_of_tens > 0)
                *code++ = '>';
                memset(code, '+', number_of_tens);
                code += number_of_tens;
                strcpy(code, "[<");
                code += 3;
                memset(code, character_in_loop, 10);
                code += 10;
                strcpy(code, ">-]<");
                code += 4;


                memset(code, character_in_loop, number_of_ones);
                code += number_of_ones;
                *code++ = '.';

                assert(brainfuck_code + code_len == code);

                return brainfuck_code;


                I added the assert at the end because these explicit length calculations can always go wrong. If the compiler is smart enough, it will find out that this assertion always succeeds and may even eliminate it. And in case you forgot a character to change the code later, you will quickly get a crash dump instead of undefined behavior because of a buffer overflow.



                I suspected you had already calculated the length wrong because I couldn't find the first character in the formula. Instead, there's a magic number 2 in that formula. You should make the formula correspond to the actual code by writing it like this:



                size_t code_len = 1 + number_of_tens + 3 + 10 + 4 number_of_ones + 1;


                This allows you to quickly compare it to the code.



                Even better would be if you would not need this whole calculation at all. Since you are writing the output to a file anyway, you don't need to allocate the memory yourself. I'm thinking of two functions like these:



                typedef struct 
                FILE *out;
                bfgen;

                static void bfgen_emit_str(bfgen *gen, const char *code)
                ...


                static void bfgen_emit_repeat(bfgen *gen, char code, size_t n)
                ...



                Then you can simply write:



                static void
                bfgen_emit_difference(bfgen *gen, int difference)
                if (difference == 0)
                bfgen_emit_str(".");
                return;


                char character_in_loop = difference > 0 ? '+' : '-';
                unsigned int abs_diff = difference > 0 ? difference : -difference;
                unsigned int number_of_tens = abs_diff / 10;

                if (number_of_tens > 0)
                bfgen_emit_str(gen, ">");
                bfgen_emit_repeat(gen, '+', number_of_tens);
                bfgen_emit_str(gen, "[<");
                bfgen_emit_repeat(gen, character_in_loop, 10);
                bfgen_emit_str(gen, ">-]<");


                bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);
                bfgen_emit_str(gen, ".");



                This code looks much clearer. Now that you don't have to think about all this annoying buffer size calculation anymore, it becomes much easier to add new optimizations, such as avoiding the loop when number_of_tens is exactly 1. In the previous version of the code I wouldn't have added this feature out of laziness and fear of breaking things.



                Based on this example, you can see that the functions bfgen_emit_str and bfgen_emit_repeat are really useful, and implementing them is easy.



                static void bfgen_emit_str(bfgen *gen, const char *code) 
                fputs(code, gen->out);


                static void bfgen_emit_repeat(bfgen *gen, char code, size_t n)
                for (size_t i = 0; i < n; i++)
                fputc(code, gen->out);




                Looking at bfgen_emit_difference again, that function doesn't do what its name says. It doesn't only emit code to calculate the difference, it also emits code to print the resulting character. It shouldn't do that. The call to bfgen_emit_str(gen, ".") belongs in bfgen_generate_code instead.




                It doesn't matter anymore, but your original version of int_to_brainfuck was essentially:



                static char *
                int_to_brainfuck(...)
                if (condition)
                return ".";
                else
                return allocated_string;




                You must never write such a function since the caller cannot know whether they should free the string or not. This leads either to memory leaks or to undefined behavior. You don't want either of these.




                In the main function, you should open the input file in binary mode and the output file in text mode. Currently it's the other way round.




                The main takeaway from this code review is that it makes sense to define your own data structures and the corresponding functions. Make these functions as easy as possible to use. Free the caller from any unnecessary tasks such as calculating buffer sizes or managing memory, which are really boring and error-prone.



                An idea for further work is to make the generated code more efficient by keeping track of the actual memory contents. This can now be easily done in the struct bfgen. Then you can look which memory cell has currently the closest value and use that instead of just using a single memory cell.



                The rewritten and restructured code is:



                #include <errno.h>
                #include <stdio.h>
                #include <stdlib.h>
                #include <string.h>

                #define FILE_ERROR 2
                #define OTHER_ERROR 3

                static FILE *
                xopen(const char *filename, const char *mode)
                FILE *file_pointer = fopen(filename, mode);
                if (file_pointer == NULL)
                fprintf(stderr, "Error: failed to open file '%s': %sn",
                filename, strerror(errno));
                exit(FILE_ERROR);

                return file_pointer;


                typedef struct
                FILE *out;
                bfgen;

                static void
                bfgen_emit_str(bfgen *gen, const char *code)
                fputs(code, gen->out);


                static void
                bfgen_emit_repeat(bfgen *gen, char code, size_t n)
                for (size_t i = 0; i < n; i++)
                fputc(code, gen->out);



                static void
                bfgen_emit_difference(bfgen *gen, int difference)
                if (difference == 0)
                return;


                char character_in_loop = difference > 0 ? '+' : '-';
                unsigned int abs_diff = difference > 0 ? difference : -difference;
                unsigned int number_of_tens = abs_diff / 10;

                if (number_of_tens > 0)
                bfgen_emit_str(gen, ">");
                bfgen_emit_repeat(gen, '+', number_of_tens);
                bfgen_emit_str(gen, "[<");
                bfgen_emit_repeat(gen, character_in_loop, 10);
                bfgen_emit_str(gen, ">-]<");


                bfgen_emit_repeat(gen, character_in_loop, abs_diff % 10);


                static void
                bfgen_generate_code(bfgen *gen, FILE *input_file)
                int current_char, last_char = 0;
                while ((current_char = fgetc(input_file)) != EOF)
                bfgen_emit_difference(gen, current_char - last_char);
                bfgen_emit_str(gen, ".n");
                last_char = current_char;



                static void
                parse_args(int argc)
                if (argc != 3)
                puts("Usage: bfgen <input> <output>");
                exit(OTHER_ERROR);



                int
                main(int argc, char **argv)
                parse_args(argc);
                FILE *input_file = xopen(argv[1], "rb");
                FILE *output_file = xopen(argv[2], "w");
                bfgen gen = output_file;
                bfgen_generate_code(&gen, input_file);
                fclose(output_file);
                fclose(input_file);
                return 0;







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 1 hour ago

























                answered 1 hour ago









                Roland IlligRoland Illig

                11.5k11946




                11.5k11946



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid …


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217422%2fprogram-that-generates-brainfuck-code-that-outputs-given-text%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    What does “fit” mean in this sentence? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)How does 'jealousy' mean 'suspicion'?What does “not so say” mean?Does “somebody of my caliber” mean the speaker themselves?“accounting for high fasting blood glucose”- help about the meaningWhat does “cloaked by NDA” mean in this context?What does it mean by 'community ownership' in this context?What does “human corroborators” mean in this context?What does “everything but a fire” mean in this context?What does “run” mean here?What does “rabbited” mean/imply in this sentence?

                    History of India Contents Prehistoric era (until c. 3300 BCE) Bronze Age – "First urbanisation" (c. 3300 – c. 1800 BCE) Climate change, de-urbanisation, and Indo-Aryan migrations (c.1800 – 1500 BCE) Iron Age - Vedic period (c. 1500 – c. 600 BCE) "Second urbanisation" (c. 600 – c. 200 BCE) Classical to early medieval periods (c. 200 BCE – c. 1200 CE) Late medieval period (c. 1200 – 1526 CE) Early modern period (c. 1526–1858 CE) Modern period and independence (after c. 1850 CE) Historiography See also References Further reading External links Navigation menureviewedee[update]The crisisThe Evolution and History of Human Populations in South Asia: Inter-disciplinary Studies in Archaeology, Biological Anthropology, Linguistics and GeneticsThe Ancient Indus: Urbanism, Economy, and Society"Indus River Valley Civilizations"The Ancient Indus: Urbanism, Economy, and Society"India before the British: The Mughal Empire and its Rivals, 1526–1857"Why Europe Grew Rich and Asia Did Not: Global Economic Divergence, 1600–1850Development Centre Studies The World Economy Historical Statistics: Historical StatisticsDeveloping cultures: case studiesEthnic Groups of South Asia and the Pacific: An Encyclopedia: An Encyclopedia"Indian Economy During British Rule""Economic Impact of the British Rule in India | Indian History"The Bone Readers: Science and Politics in Human Origins Research"Out of Africa: new hypotheses and evidence for the dispersal of Homo sapiens along the Indian Ocean rim"10.3109/0301446100363924920334598"Genetic and archaeological perspectives on the initial modern human colonization of southern Asia"2013PNAS..11010699M10.1073/pnas.1306043110369678523754394"Edakkal Caves|Places Around in Wayanad"Protecting megaliths to keep history alive The Hindu daily"Archaeologists rock solid behind Edakkal Cave"The Global Prehistory of Human Migration"Indus Valley 2,000 years older than thought"the original"Stepwells -Cosmology of Subterranean Architecture as seen in Adalaj"A History of Ancient and Early medieval India : from the Stone Age to the 12th century"Stone celts in Harappa"the original"Peoples and languages in pre-islamic Indus valley"the original"The Sindhi language"the originalThe Aryan chromosome"Fluvial landscapes of the Harappan Civilization"2012PNAS..109E1688G10.1073/pnas.1112743109338705422645375"Is River Ghaggar, Saraswati? Geochemical Constraints""An Ancient Civilization, Upended by Climate Change""Huge Ancient Civilization's Collapse Explained"2003GeoRL..30.1425S10.1029/2002GL0168222006QSRv...25.1283M10.1016/j.quascirev.2005.10.0122011QuInt.229..140M10.1016/j.quaint.2009.11.012Climate Change and the Course of Global History: A Rough JourneyA History of Ancient and Early Medieval India: From the Stone Age to the 12th CenturyA History of Ancient and Mediaeval India: From the Stone Age to the 12th CenturyAntennae SwordA History of IndiaA History of IndiaAn Introduction to Hinduism"India: The Late 2nd Millennium and the Reemergence of Urbanism"The Coinage of Ancient IndiaA Sanskrit reader: with vocabulary and notesPedigree: the origins of words from nature"Early Sanskritization. Origins and Development of the Kuru State"10.11588/ejvs.1995.4.823The Sanskrit epics, Part 2The City in South AsiaThe UpanishadsAn Introduction to HinduismReligions of the World, Second Edition: A Comprehensive Encyclopedia of Beliefs and PracticesA History of Ancient and Early Medieval India: From the Stone Age to the 12th CenturyEarly India: From the Origins to AD 1300Republics in ancient Indiapp. 83ff"Magadha Empire""Lumbini Development Trust: Restoring the Lumbini Garden"the originalThe great armies of antiquityarchived"The Achaemenid Persian Empire (550–330 B.C.)""East–West Orientation of Historical Empires"1076-156X"Dinner on the Grand Trunk Road"10.2307/32502263250226"Silappathikaram Tamil Literature"the originalManimekalai – English transliteration of Tamil originalIndian Temple Architecture: Form and Transformation : the Karṇāṭa Drāviḍa Tradition, 7th to 13th CenturiesBuddhist ArchitectureA History of India"The World Economy (GDP) : Historical Statistics by Professor Angus Maddison"The World Economy – Volume 1: A Millennial Perspective and Volume 2: Historical Statistics10.2307/32502140004-36483250214A Comprehensive History of India: Volume 2Between the Empires: Society in India, 300 to 400Emergence of Viṣṇu and Śiva Images in India: Numismatic and Sculptural Evidence"Parthian Pair of Earrings"the originalThe Medical Times and Gazette, Volume 1Greatest emporium in the worldThe Cambridge History of Ancient China: From the Origins of Civilization to 221 BCBuddhist Records of the Western WorldArchaeology in Soviet Central AsiaThe Grandeur of Gandhara: The Ancient Buddhist Civilization of the Swat, Peshawar, Kabul and Indus ValleysIndian Sculpture: Circa 500 B.C.-A.D. 700"The History of Pakistan: The Kushans"Gupta Dynasty – MSN Encartathe original"India – Historical Setting – The Classical Age – Gupta and Harsha""Gupta Dynasty, Golden Age Of India"the original"The Age of the Guptas and After"the originalNumber Theory and Its History"Gupta dynasty (Indian dynasty)""Gupta dynasty: empire in 4th century"the original"The Story of India – Photo Gallery"The ASI say499315420"Pallava script"p. 145"CNG: eAuction 329. INDIA, Post-Gupta (Ganges Valley). Vardhanas of Thanesar and Kanauj. Harshavardhana. Circa AD 606–647. AR Drachm (13mm, 2.28 g, 1h)""Harsha""Sthanvishvara (historical region, India)""Harsha (Indian emperor)"Shyama Kumar Chattopadhyaya (2000) The Philosophy of Sankar's Advaita VedantaShankara's IntroductionShankara's Introduction19373677Shankara's IntroductionIs The Buddhist 'No-Self' Doctrine Compatible With Pursuing Nirvana?The Seven Spiritual Laws Of YogaIndia: The Ancient Past. A History of the Indian-Subcontinent from 7000 BC to AD 1200The Kashmir Series: Glimpses of Kashmiri Culture – Vivekananda Kendra, Kanyakumari (p. 57).Al-Hind: Early Medieval India and the Expansion of Islam, 7th–11th CenturiesHistory of GopāchalaLand of Two Rivers: A History of Bengal from the Mahabharata to MujibEuropean Trade and Colonial ConquestA History of IndiaA Comprehensive History Of Ancient India (3 Vol. Set)"The Last Years of Cholas: The decline and fall of a dynasty"the originalFascinating Hindutva: Saffron Politics and Dalit MobilisationGazetteer of the province of OudhAl- Hind: The slave kings and the Islamic conquest. 2"Shahi Family"The Cambridge history of Islam"Ameer Nasir-ood-deen Subooktugeen"Gazetteer of the Attock District, 1930, Part 1Land of seven rivers: History of India's GeographyTemple Desecration and Indo-Muslim StatesIslam in South Asia: A Short HistoryBeyond Orientalism: The Work of Wilhelm Halbfass and Its Impact on Indian and Cross-cultural StudiesThe Making of Terrorism in Pakistan: Historical and Social Roots of ExtremismOrnament in Indian ArchitectureA historical review of Hindu India: 300 B.C. to 1200 A.D."Indian States and Union Territories"Islam in South Asia: A Short HistoryA Brief History of the Indian PeoplesThe Modern ReviewDelhi Sultanate"Battuta's Travels: Delhi, capital of Muslim India"the original"Timur – conquest of India"the originalIndia HandbookBhaktiThe Four Denomination of Hinduism10.1007/s11407-008-9049-925691067"Vijayanagara Research Project::Elephant Stables"10.2307/26465262646526Historical Dictionary of the TamilsBihar General Knowledge DigestMapping Bihar: From Medieval to Modern TimesPopular Literature and Pre-modern Societies in South AsiaA manual of the Kistna district in the presidency of MadrasAncient Indian History and CivilizationFragmented Memories: Struggling to be Tai-Ahom in India"The Islamic World to 1600: Rise of the Great Islamic Empires (The Mughal Empire)"the originalDynasties: A Global History of Power, 1300–1800, p. 105"Whose fort is it anyway"10.1111/0020-8833.000532600793Development Centre Studies The World Economy Historical Statistics: Historical Statistics"India's Deindustrialization in the 18th and 19th Centuries"The Mughal Empire, p. 190"The Long Globalization and Textile Producers in India"The Mughal World: Life in India's Last Golden AgeAurangzeb: The Life and Legacy of India's Most Controversial KingIn the Shadow of the Taj: A Portrait of Agra"Iran in the Age of the Raj"p. 8610.2307/20539802053980Delhi, the Capital of IndiaAn Advanced History of Modern India"Journal of the Tanjore Maharaja Serfoji's Sarasvati Mahal Library"The Rediscovery of India: A New SubcontinentIslamic Renaissance In South Asia (1707–1867) : The Role Of Shah Waliallah & His SuccessorsAn Advanced History of Modern IndiaThe Great Maratha Mahadaji Scindia"Full text of "Selections from the papers of Lord Metcalfe; late governor-general of India, governor of Jamaica, and governor-general of Canada""The Discovery Of IndiaThe Sacred City of the Hindus: An Account of Benares in Ancient and Modern TimesResurrecting Banaras: Urban Space, Architecture and Religious BoundariesFaith & Philosophy of Sikhism"Missiles mainstay of Pak's N-arsenal"History Modern India By S.N. Sen"Sirajuddaula"ArchivedLongman History & Civics (Dual Government in Bengal)Madhya Pradesh National Means-Cum-Merit Scholarship Exam (Warren Hasting's system of Dual Government)A Military History of Britain: from 1775 to the PresentIndian Cultural Heritage Perspective For TourismHindu Rulers, Muslim Subjects: Islam, Rights, and the History of KashmirIndian HistoryAn Atlas and Survey of South Asian HistoryAn Historical Account of the British Trade Over the Caspian SeaIndian Merchants and Eurasian Trade, 1600–1750The Indian diaspora in Central Asia and its trade, 1550–1900From Constantinople to the home of Omar Khayyam: travels in Transcaucasia and northern Persia for historic and literary researchA journey from Bengal to England: through the northern part of India, Kashmire, Afghanistan, and Persia, and into Russia, by the Caspian-SeaA Second Journey through Persia, Armenia, and Asia Minor, to Constantinople, between the Years 1810 and 1816Reports from the consuls of the United States, 1887Portugal and its Empire, 1250–1800 (Collected Essays in Memory of Glenn J. Ames).: Portuguese Studies Review, Vol. 17, No. 1The Dutch Power in Kerala, 1729–1758http://mod.nic.inArchivedDossier Goa – A Recusa do Sacrifício InútilAn Imperial Crisis in British India: The Manipur Uprising of 1891The Truth of Babri Mosque"Kolkata (Calcutta) : History"the original"Robert Clive, Baron Clive, 'Clive of India', 1725–1774""The Transformation from a Pre-Colonial to a Colonial Order: The Case of India"10.2307/25955872595587A versatile geniusArchived10.1109/MWSYM.1997.602854"Rabindranath Tagore on Education"the original"Essay on 'Derozio and the Young Bengal Movement'"Poverty and Famines: An Essay on Entitlement and Deprivation"Plague"the originalPopulation Growth and Land Use"Reintegrating India with the World Economy""Census Of India 1931"A history of modern India, 1480–1950"'India's well-timed diversification of army helped democracy' | Business Standard News"Bal Gangadhar Tilak: Struggle for Swaraj"Participants from the Indian subcontinent in the First World War""Commonwealth War Graves Commission Annual Report 2007–2008 Online"the original1462689197110.1017/s0010417500016534178920Eurocentrism: a marxian critical realist critique"Ranjit Guha, "On Some Aspects of Historiography of Colonial India""10.2307/2168385216838510.7202/016593ar"Harvard scholar says the idea of India dates to a much earlier time than the British or the Mughals""In The Footsteps of Pilgrims""India's spiritual landscape: The heavens and the earth""India: A Sacred Geography by Diana L Eck – review"Modern India: The Origins of an Asian Democracy10.2307/21694222169422964322464"The Indian Subcontinent and 'Out of Africa 1'"254043308Encyclopedia of World ReligionsThe Evolution and History of Human Populations in South Asia: Inter-disciplinary Studies in Archaeology, Biological Anthropology, Linguistics and Genetics"The Early Paleolithic of the Indian Subcontinent: Hominin Colonization, Dispersals and Occupation History"Ancient Indian History and CivilizationAncient Indian Social History: Some Interpretationsthe originalIndia Before EuropeA Concise History of Modern India"The beginning of the historical period, c. 500–150 BCE"full textA History of Indiathe originalexcerpt and text searchexcerptexcerptAn Economic History of India: From Pre-Colonial Times to 1991excerpt and text searchexcerpt and text searchIndia as known to the ancient world10.1111/j.1468-0289.1985.tb00391.x2597191onlineThe History of India, as told by its own historians. The Muhammadan Periodonline editionHans William Brown research collection on 19th-century missionary work in India, 1882–1932, Ms. Coll. 1033, Kislak Center for Special Collections, Rare Books and Manuscripts, University of Pennsylvaniaee

                    Isurus Índice Especies | Notas | Véxase tamén | Menú de navegación"A compendium of fossil marine animal genera (Chondrichthyes entry)"o orixinal"A review of the Tertiary fossil Cetacea (Mammalia) localities in wales port taf Museum Victoria"o orixinalThe Vertebrate Fauna of the Selma Formation of Alabama. Part VII. Part VIII. The Mosasaurs The Fishes50419737IDsh85068767Isurus2548834613242066569678159923NHMSYS00210535017845105743