0

So I was playing around with pointers and malloc and while I was doing it I got completely confused by my code working when it's not supposed to.(I think?) Here is my code:

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

void test1() {
  int arr[10];

  for (int i = 0; i < 20; i++) {
    printf("%i ", arr[i]);
  }

  printf("\n");
}

void test2() {
  char *thing = (char *)malloc(10 * sizeof(char));

  for (int i = 0; i < 25; i++) {
    thing[i] = 'A';
  }

  for (int i = 0; i < 30; i++) {
    printf("%c ", thing[i]);
  }

  thing[10] = 'B';

  printf("%c\n", thing[10]);
}

int main() {
  // test1();
  test2();

  return 0;
}

In test2, I think I am allocating 10 blocks of memory of size char or 10 bytes of memory. But somehow thing[i] can be written to, for i ranging between 0 all the way to 25.

I then try to print 30 elements starting from pointer thing and i successfully manage to do so.

On output I get this

A A A A A A A A A A A A A A A A A A A A A A A A       B

My question is:

Why was I able to write and read 25 A's when I only allocated 10 bytes of memory?

Thanks in advance!

  • 1
    Also see [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). That is, buggy code with UB can crash, get wrong results, even appear to "work" and any other unpredictable behaviour at any time and place. – kaylum Oct 10 '21 at 23:25

0 Answers0