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

int main()
{
    char *p = malloc(10);
    int i;
    for(i=0;i<15;i++)
    {
        p[i]='c';
        printf("INDEX:%d  %c\n",i,p[i]);
    }

    return 0;
}

I'm not sure why in the above code, I only allocated memory of 10 but I am still able to access the 15th index of the pointer.

I'm not sure why but I thought it would be because this pointer points to some random chunk of memory and I'm just overwriting that part of the memory, but I'm only allocating a specific amount of memory so I'm not sure why it would work.

Can someone confirm?

jfgao
  • 25
  • 3

2 Answers2

5

I'm not sure why in the above code, I only allocated memory of 10 but I am still able to access the 15th index of the pointer.

Accessing memory beyond what you requested is cause for undefined behavior. You should consider yourself unlucky if the program does not crash. It will behave strangely at the most inopportune moment.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
4

In C, When you access array with out of bound index, according to C language, the behavior is undefined, Since C/C++ doesn't actually do any boudary checking with regards to arrays. It only depends on the OS to ensure that you are accessing valid memory.

Why you does not see an error

In short, you are lucky.

Usually arrays are allocated in adjacent memory address. When you add your pointer, compiler will simply generate code to access the adjacent memory. Since it is still in your program's memory space, Operating System does not trigger error for this.

How to check such kind of error

There are some tools, like valgrind, and also some helpful compiler flags which could be used to detect some of these errors.

For example, if you run the generated binary in valgrind, valgrind will generate following messages when write to p[10]

==14590== Invalid write of size 1
==14590==    at 0x4005B2: main (in /home/lingkun/Develop/courage/cpp/src/a.out)
==14590==  Address 0x520204a is 0 bytes after a block of size 10 alloc'd
==14590==    at 0x4C2BBA0: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14590==    by 0x400597: main (in /home/lingkun/Develop/courage/cpp/src/a.out)
==14590== 
==14590== Invalid read of size 1
==14590==    at 0x4005C2: main (in /home/lingkun/Develop/courage/cpp/src/a.out)
==14590==  Address 0x520204a is 0 bytes after a block of size 10 alloc'd
==14590==    at 0x4C2BBA0: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14590==    by 0x400597: main (in /home/lingkun/Develop/courage/cpp/src/a.out)
==14590== 
INDEX:10  c
INDEX:11  c
INDEX:12  c
INDEX:13  c
INDEX:14  c
Kun Ling
  • 2,211
  • 14
  • 22