سؤال

In the simple program below command is pointing to 400 bytes on the heap. Then I copy "./search '" to command, *buffer points to the next byte after " ' " (single quote). Starting the memory pointed by buffer I use memset to set 300 bytes to value 0x41 (ASCII 'A'), then I append the closing single quote.

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

But when I look at *command and *buffer in gdb this is what I see.

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

First I was expecting it to say repeats 299 times and second I was expecting both command and buffer repeats to be of similar value. Can someone please tell me what am I missing?

هل كانت مفيدة؟

المحلول

From the GDB manual, section 10.8 Print Settings:

set print elements number-of-elements

Set a limit on how many elements of an array gdb will print. If gdb is printing a large array, it stops printing after it has printed the number of elements set by the set print elements command. This limit also applies to the display of strings. When gdb starts, this limit is set to 200. Setting number-of-elements to zero means that the printing is unlimited.

نصائح أخرى

Checking your assumptions:

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

Produces this output:

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 ''

This looks right, and doesn't agree with the diagnosis in the question. So either gdb is broken, or you're looking at the bytes after they are freed.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top