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:
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!
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);