0
#include <stdio.h>
#include <string.h>
typedef unsigned char *byte_pointer;
        
void show_bytes(byte_pointer start, size_t len)
{
    size_t i;
    for (i = 0; i < len; i ++)
    {
        printf("%.2x", start[i]);
    }
    printf("\n");
}

void show_int(int x)
{
    show_bytes((byte_pointer) &x, sizeof(int));
}

int main()
{
    const char *s = "abcdef";
    printf("%ld\n", sizeof(s));
    printf("%ld\n", strlen(s));
    show_bytes((byte_pointer)s, sizeof(s));
    show_bytes((byte_pointer)s, strlen(s));
    return 0;
}

The output is :

8
6
6162636465660025
616263646566

Why are there two more bytes? Shouldn't there be just one more ending null?

Can someone tell me what the last byte of the sizeof output represents?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    `sizeof(const char *)` -- That gives the sizeof a char pointer, not the length. That's basically what your code here is doing: `printf("%ld\n", sizeof(s));` – PaulMcKenzie Mar 06 '21 at 05:58
  • Thanks,I understand this point. emm, I know '00' represents "null", but what the last '25' mean? – Crepuscule_v Mar 06 '21 at 06:36
  • @Crepuscule_v it is just random data from surrounding memory. `s` is pointing at an array of 7 bytes but you are displaying `sizeof(s)` (8) bytes from it, so you are going out of bounds. – Remy Lebeau Mar 06 '21 at 06:57
  • I got it. It means that char * is eight bytes in size on a 64-bit machine, and the result of the `sizeof(s)` depends on type of `s` rather than content of `s`, Thanks for your answer! – Crepuscule_v Mar 06 '21 at 07:07

0 Answers0