0

Size of an int is 4 bytes and I am allocating only 1 byte.

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

int main(int argc, char ** argv) {
    int *a = (int *) malloc(1);

    // But I am still able to store int.
    *a = 42;
    printf("%d\n", *a);

    // It also allowed me to store char in an int pointer.
    *a = 'H';
    printf("%c\n", *a);
}
ldav1s
  • 15,885
  • 2
  • 53
  • 56
Legend
  • 15
  • 5
  • 3
    Are you asking why undefined behavior sometimes does what you want? – Tom Karzes Dec 30 '20 at 01:25
  • @Tom Krazes yes – Legend Dec 30 '20 at 01:26
  • There are probably a very large number of duplicates of this question on the site and I'm not sure how best to resolve that. Is there a canonical best one we should keep? – R.. GitHub STOP HELPING ICE Dec 30 '20 at 01:34
  • @R..GitHubSTOPHELPINGICE: I chose a fairly old, fairly highly voted one that covered a nearly identical case (allocate one byte, store more). Seemed more than close enough. – ShadowRanger Dec 30 '20 at 01:36
  • Side-note: On "It also allowed me to store char in an int pointer"; one, that would be legal if you'd allocated enough memory for it in any event (it would just expand it to `int` size), but two, `'H'` is actually an `int` in C (character literals are of type `int` in C, yes it's odd, and no, it's not the same in C++, where character literals are in fact of type `char`). – ShadowRanger Dec 30 '20 at 01:38

1 Answers1

2

This:

int* a = (int*) malloc(1);
*a = 42;

Is undefined behavior. It might seem to work for now, but maybe not later. But in practice, you've corrupted the heap. All bets are off on what your program's behavior might be - especially as you add more code and do more malloc/free calls later.

This statement:

*a='H';

Is also unsafe. It's equivalent to this:

*a = (int)'H';

Which is equivalent to this (assuming ascii):

*a = 72;

You're probably getting lucky because malloc likely allocates memory on word aligned boundaries. But don't design your program to rely on that.

selbie
  • 100,020
  • 15
  • 103
  • 173