【问题标题】:memset not setting num bytes?memset 没有设置 num 字节?
【发布时间】:2013-01-18 11:26:42
【问题描述】:

在下面的简单程序中,命令指向堆上的 400 个字节。然后我将“./search '”复制到命令,*buffer 指向“'”(单引号)之后的下一个字节。启动缓冲区指向的内存,我使用 memset 将 300 个字节设置为值 0x41(ASCII 'A'),然后附加结束单引号。

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

int main(int argc, char *argv[]) {
    char *command = (char *)malloc(400);
    bzero(command, 400);

    strcpy(command, "./search \'");
    char *buffer = command + strlen(command);

    memset(buffer, 0x41, 300);
    strcat(command, "\'");

    system(command);
    free(command);
}

但是当我在 gdb 中查看 *command 和 *buffer 时,我看到的就是这个。

char * command 0x601010 "./search '", 'A' <repeats 186 times>...
char * buffer  0x60101e 'A' <repeats 200 times>...

首先我希望它说重复 299 次,其次我希望命令和缓冲区重复具有相似的值。有人可以告诉我我错过了什么吗?

【问题讨论】:

  • command 被释放后是否查看其字节?
  • 这些转义引号 ("\'") 在我看来很奇怪...
  • memset(buffer, 'A', 300);会更具可读性... :)
  • 对我来说似乎是一个 GDB 显示错误:P

标签: c gdb memset


【解决方案1】:

来自GDB manual, section 10.8 Print Settings

设置打印元素元素数

设置一个数组 gdb 将打印多少元素的限制。如果 gdb 正在打印一个大数组,它会在打印完由 set print elements 命令设置的元素数量后停止打印。此限制也适用于字符串的显示。当 gdb 启动时,此限制设置为 200。将元素数量设置为零意味着打印不受限制。

【讨论】:

    【解决方案2】:

    检查你的假设:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <strings.h>
    
    int main(int argc, char *argv[]) {
        char *command = (char *)malloc(400);
        bzero(command, 400);
    
        strcpy(command, "./search \'");
        char *buffer = command + strlen(command);
    
        memset(buffer, 0x41, 300);
        strcat(command, "\'");
        int last = -1;
        int n = 0;
        for (int i = 0; i < 400; i++) {
            if (n && command[i] != last) {
                printf("%d %d x %02x '%c'\n", i - n, n, last, last);
                n = 1;
            } else {
                n++;
            }
            last = command[i];
        }
        printf("%d %d x %d '%c'\n", 400 - n, n, last, last);
        return 0;
    }
    

    产生这个输出:

    0 1 x 2e '.'
    1 1 x 2f '/'
    2 1 x 73 's'
    3 1 x 65 'e'
    4 1 x 61 'a'
    5 1 x 72 'r'
    6 1 x 63 'c'
    7 1 x 68 'h'
    8 1 x 20 ' '
    9 1 x 27 '''
    10 300 x 41 'A'
    310 1 x 27 '''
    311 89 x 0 ''
    

    这看起来是正确的,并且与问题中的诊断不符。所以要么 gdb 坏了,要么你正在查看它们被释放后的字节。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      相关资源
      最近更新 更多