-2

Consider the following code:

int *p;
p = malloc(1);//p can point to 1 byte memory area

Why can p point to many memory areas like below?

printf("%p %p %p %p %p",p,p+1,p+2,p+3,p+4);
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
T1412
  • 1
  • There are no training-wheels on C. You can make `p = 0;` and then dereference `p` just to enjoy the SegFault. Knowing what memory you have allocated and what is valid is all up to you... That is where C derives a great deal of its blistering speed. It places the responsibility of properly "programming" on you. If you allocate `1-byte` it is up to you to ensure no more than `1-byte` is every accessed with that allocation. This is just the way it should be. You, the programmer, have complete control over every byte of memory your program uses -- use it wisely. – David C. Rankin Nov 05 '18 at 06:01

2 Answers2

1

The cases p+1, p+2 and so on, cause undefined behaviour. As described by that page, your program doesn't comply with the rules of the C language so any behaviour you might get is meaningless.

M.M
  • 138,810
  • 21
  • 208
  • 365
0

C doesn't do any memory address checking. It's one of the things that makes c incredibly efficient, but also more difficult to program. A pointer is just a variable like any other, storing binary data, and distinguished only by the fact that the data is expected to be a memory address. Pointer arithmetic is perfectly valid in the case of, for example, c arrays.

You could also set a pointer to a random or arbitrary value. But unless you engineer it as such, dereferencing any address not from the compiler or malloc will result in either access of some of your own programs memory space, or a segmentation fault.

erik258
  • 14,701
  • 2
  • 25
  • 31
  • Pointer arithmetic is only valid within the bounds of an object (or one past the end) – M.M Nov 05 '18 at 03:56