0
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *p = malloc(sizeof(void));
    p[0] = 'a';
    p[1] = 'b';
    p[2] = 'c';
    p[3] = 'd';
    p[4] = 'e';
    printf("%c\n",p[0]);
    printf("%c\n",p[1]);
    printf("%c\n",p[2]);
    printf("%c\n",p[3]);
    printf("%c\n",p[4]);
    return 0;
}

// In above code only one byte memory should be allocated as sizeof(void) will be only '1', but why I am able to successfully print all the characters?

similarly for below program also it is printing successfully

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

int main()
{
    char *p = malloc(0);
    p[0] = 'a';
    p[1] = 'b';
    p[2] = 'c';
    p[3] = 'd';
    p[4] = 'e';
    printf("%c\n",p[0]);
    printf("%c\n",p[1]);
    printf("%c\n",p[2]);
    printf("%c\n",p[3]);
    printf("%c\n",p[4]);
    return 0;
}

Please clarify why both of this cases are successfully printing the msg even though memory is not allocated for this?

sagar
  • 99
  • 1
  • 1
  • 3

1 Answers1

0

You're exploiting undefined behaviour.

On other occasions the compiler might eat your cat.

(What might be happening under the hood is that the C runtime library is giving you back more memory than you've actually asked for as some kind of optimisation.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483