GDB - Print Bit Values of Bytes

| Comments

Print bit values in a byte

Recently, I have been working on interesting piece of code whose crux is to create a array of pointer addresses. Each entry in this array is address pointing to memory location.

For example
Container array contains char addresses. Here, 100 is memory address where char value resides.

10010002000


Address 100

vaibhav\0


Sometimes char data type is used as a package of 8 bits not as a valid char value.

Code snippet

Print bit values
 1
 2#include <stdio.h>
 3#include <stdlib.h>
 4#include <string.h>
 5
 6int main()
 7{
 8    char **container = (char **)malloc(10 * sizeof(char*));
 9    char **start = container;
10    char *node;
11
12    char name[] = "Vaibhav";
13    int i = 0;
14
15    if (container == NULL) {
16    return 0;
17    }
18
19    for (i = 0; i <= 2; i++) {
20    node = (char *)malloc(10 * sizeof(char));
21    memcpy(node, &name, strlen(name) + 1); 
22    *container = node;
23    container++;
24    }
25    *container = NULL;
26
27    while (*start != NULL) {
28    printf("%s\n", *start);
29    start++;
30    }
31
32    return 0;
33}


Focusing on following code section

1for (i = 0; i < = 2; i++) {
2    node = (char *)malloc(10 * sizeof(char));
3    memcpy(node, &name, strlen(name) + 1); 
4    *container = node;
5    container++;
6}


In this section, a memory of 10 chars is being allocated, initialized and finally assigned to container array.
Lets observer, if we have set the right information in each char bit.

Compile code using for GDB
gcc -g fileName.c


GDB Trace
 1
 2(gdb) l
 316      }
 417    
 518        for (i = 0; i < = 2; i++) {
 619            node = (char *)malloc(10 * sizeof(char));
 720            memcpy(node, &name, strlen(name) + 1);
 821            *container = node;
 922            container++;
1023        }
1124        *container = NULL;
1225    
13(gdb) ptype node
14type = char *
15(gdb) p node
16$1 = 0x1001000e0 "Vaibhav"
17(gdb) x/8bb node
180x1001000e0:    0x56    0x61    0x69    0x62    0x68    0x61    0x76    0x00
19(gdb) x/8ub node
200x1001000e0:    86    97    105    98    104    97    118    0
21(gdb) x/8tb node
220x1001000e0:    01010110    01100001    01101001    01100010    01101000    01100001    01110110    00000000

debug

Process synchronization in OS »

Comments