1

As I found on one site following code:

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

int main(void) 
{
    int *p1 = malloc(4*sizeof(int));  // allocates enough for an array of 4 int
    int *p2 = malloc(sizeof(int[4])); // same, naming the type directly
    int *p3 = malloc(4*sizeof *p3);   // same, without repeating the type name

    if(p1) {
        for(int n=0; n<4; ++n) // populate the array
            p1[n] = n*n;
        for(int n=0; n<4; ++n) // print it back out
            printf("p1[%d] == %d\n", n, p1[n]);
    }

    free(p1);
    free(p2);
    free(p3);
}

Output:

p1[0] == 0

p1[1] == 1

p1[2] == 4

p1[3] == 9

Now following that code above I did this:

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

int main()

{

    int  *ip = (int*)malloc(1 * sizeof(int));

    ip[0] = 2;
    ip[1] = 9;

    printf("%d %d",ip[0],ip[1]);



    return 0;
}

Output: 2 9

So how then my pointer *ip can store more than one int when I only allocated bytes for single int?

Hury H
  • 31
  • 7
  • 2
    A small program like this will probably work. But once you start adding more statements after the undefined behavior, things might get corrupted and you'll see unexpected results. So basically, it's just wrong. – DeiDei Mar 03 '19 at 20:43

2 Answers2

5

You're writing into memory which is outside of the bounds of the array. Sadly, there is no compiler check for this, but it sometimes works.

Note: This is undefined behavior and should not be used under any circumstances.

unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
3

Remember, ip[1] is equivalent to *(ip + 1), which is syntactically valid for any pointer, even if ip is pointing to single int and not an array of ints.

Dereferencing or writing to ip[1] is undefined behavior. Try adding free(ip) before the return 0 in your second program and observe the behavior then.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
  • As someone who doesn’t program in C, I’d love to know what is the behavior that can be observed when you add `free(ip)` before the `return 0`. – Marcos Dimitrio Mar 05 '19 at 17:23
  • @MarcosDimitrio Normally, you will crash on a call to `free` if you wrote beyond your allocated space. But undefined behavior is undefined behavior; anything may happen – Govind Parmar Mar 05 '19 at 17:26