Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error with C code when compiling with assembly code

I’m currently using a book to learn a little bit of assembly. The part of the book I’m in is about malloc and free. To understand it better the book provides assembly code that creates a simple malloc and free implementation, which is then used by another small c program:

#include<stdio.h>

void *allocate(int);
void deallocate(void *);

int main() {

    char *a1 = allocate(500);
    char *a2 = allocate(1000);
    char *a3 = allocate(100);

    fprintf(stdout, "Allocations: %d, %d, %d\n", a1, a2, a3);

    deallocate(a1);

    char *a4 = allocate(1000);
    char *a5 = allocate(250);
    char *a6 = allocate(250);
    fprintf(stdout, "Allocations: %d, %d, %d, %d, %d, %d\n", a1, a2, a3, a4, a5, a6);

    fscanf(stdin, "%s", a5);
    fprintf(stdout, "%s\n", a5);

}

I get the assembly code but after compiling the two together in the Linux terminal with:

gcc -static allocate.s usealloc.c -o usealloc

I receive multiple errors like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

usealloc.c:12:40: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘char *’ [-Wformat=]
   12 |         fprintf(stdout, "Allocations: %d, %d, %d\n", a1, a2, a3);
      |                                       ~^             ~~
      |                                        |             |
      |                                        int           char *
      |                                       %s

I’m assuming %d is expecting an argument of int, which is in conflict of a1, a2, and a3 being declared char. I’m not really familiar with C just yet but I figured a published book wouldn’t have a simple issue like this, so any help is appreciated!

>Solution :

First off, it’s great that you’re paying attention to warnings! It’s a shame the book authors didn’t.

You can make this warning go away if you explicitly cast those character pointers to int:

fprintf(stdout, "Allocations: %d, %d, %d, %d, %d, %d\n", (int) a1, (int) a2, (int) a3, (int) a4, (int) a5, (int) a6);

Better yet, use %p instead, which is used for printing nicely formatted pointers like 0x600000de0000:

fprintf(stdout, "Allocations: %p, %p, %p, %p, %p, %p\n", a1, a2, a3, a4, a5, a6);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading