可变函数

问题描述 投票:0回答:1

我应该如何设置my_printf,以便它将执行printf(“%p”)+而不使用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.
}
c printf memory-address
1个回答
0
投票

输入:

char *arr=malloc(sizeof(address));
arr=address;

分配的块丢失,这是内存泄漏

要做:

arr[strlen(arr)]='\0';

没有任何意义,如果您能够使用strlen,则意味着空字符已经存在。但是完全不确定您是否有字符串,因此无法在该指针上使用strlen。您不知道是否可以出于很多原因对其进行修改,实际上这样做是没有用的。

输入

write(1,arr,strlen(arr));

再次假设您有一个字符串,这可能是错误的,并且您的目标不是编写指向值的包含而是其地址。


一种方法是:

#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;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -Wall p.c
pi@raspberrypi:/tmp $ ./a.out
(nil) 
(nil)
0x106b8 
0x106b8
0xbec2d26c 
0xbec2d26c
0x10b1558 
0x10b1558
pi@raspberrypi:/tmp $ 

请注意,您的printf非常有限,仅管理简单格式%p

© www.soinside.com 2019 - 2024. All rights reserved.