簡體   English   中英

memset不設置數字字節?

[英]memset not setting num bytes?

在下面的簡單程序中,命令指向堆上的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次,其次,我期望命令和緩沖區重復都具有相似的值。 有人可以告訴我我想念什么嗎?

GDB手冊中,第10.8節“打印設置”

設置打印元素數

設置gdb可以打印多少個數組的限制。 如果gdb正在打印大型數組,則在打印了set print elements命令設置的元素數后,它將停止打印。 此限制也適用於字符串的顯示。 gdb啟動時,此限制設置為200。將元素數設置為零表示打印不受限制。

檢查您的假設:

#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損壞了,要么您正在查看釋放后的字節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM