问题
How should I set my_printf, so it would do what printf("%p") does + without using printf.
void my_printf(char * format, ...)
{
va_list ap;
va_start(ap, format);
if(!strcmp(format,"%p"))
{
void *address= va_arg (ap, void*);
char *arr=malloc(sizeof(address));
arr=address;
arr[strlen(arr)]='\0';
write(1,arr,strlen(arr));
}
va_end (ap);
//it has to print an address in hexadecimal format.
}
回答1:
In :
char *arr=malloc(sizeof(address)); arr=address;
the allocated block is lost, this is a memory leak
To do :
arr[strlen(arr)]='\0';
has no sense, if you are able to use strlen
that means the null character is already present.
But it is not sure at all you have a string so you cannot use strlen
on that pointer.
You do not know if you can modify it for a lot of reasons, and in fact it is useless to do that.
In
write(1,arr,strlen(arr));
again supposes you have a string, which can be wrong, and your goal is not to write the contain of the pointed value but its address.
A way to do is :
#include <stdint.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h> /* for malloc use in main */
void my_printf(char * format, ...)
{
va_list ap;
va_start(ap, format);
if (!strcmp(format,"%p"))
{
void * address= va_arg(ap, void*);
uintptr_t u = (uintptr_t) address;
if (u == 0)
fputs("(nil)", stdout);
else {
char s[2 * ((sizeof(u) * CHAR_BIT + 7) / 8) + 3];
int i = sizeof(s) - 1;
s[i] = 0;
do {
s[--i] = ((u & 0xf) < 10) ? ('0' + (u & 0xf)) : ('a' + (u & 0xf) - 10);
u >>= 4;
} while(u);
s[--i] = 'x'; /* can also putchar('0') */
s[--i] = '0'; /* can also putchar('x') */
fputs(s+i, stdout);
}
/* check */
printf("\n%p\n", address);
}
va_end (ap);
}
int main()
{
void * p = malloc(1);
my_printf("%p", 0);
my_printf("%p", &main);
my_printf("%p", &p);
my_printf("%p", p);
free(p);
return 0;
}
Compilation and execution :
pi@raspberrypi:/tmp $ gcc -Wall p.c
pi@raspberrypi:/tmp $ ./a.out
(nil)
(nil)
0x106b8
0x106b8
0xbec2d26c
0xbec2d26c
0x10b1558
0x10b1558
pi@raspberrypi:/tmp $
Note your printf is very limited and only manage the simple format %p
来源:https://stackoverflow.com/questions/61507938/varadict-functions