1

I learned about Dynamic Memory Allocation in C today. I learned how memory can be allocated to a char array with the malloc() from stdlib.h when I need to print a sentence. But then I saw I was able to store more bytes then I assigned. Here is my entire code.

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

int main(void) {
  int i;
  char *foo;
  foo = (char*)malloc(20);
  for (i=0;i<30;i++)
  {
    foo[i]='a';
    printf("\n%d) %c",i+1,foo[i]);
  }
  return 0;
}

Output

1) a
2) a
3) a
4) a
5) a
6) a
7) a
8) a
9) a
10) a
11) a
12) a
13) a
14) a
15) a
16) a
17) a
18) a
19) a
20) a
21) a
22) a
23) a
24) a
25) a
26) a
27) a
28) a
29) a
30) a

As you can see I gave foo 20 bytes but was able to store 30 bytes in it. What is going on? Did I misunderstand malloc()?

  • 2
    You can also do `foo[1000000000] = 1`. I am saying that i'ts programmers job to check the validity of the program. [Array index out of bound in C](https://stackoverflow.com/questions/671703/array-index-out-of-bound-in-c) [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) – KamilCuk Nov 06 '19 at 12:02
  • Are you saying I don't even understand arrays? – Muhammad Usman Nov 06 '19 at 12:03
  • There is no bound checks in `C`. – kiran Biradar Nov 06 '19 at 12:03
  • 1
    `Did I misunderstand malloc()` No, you misunderstood the `C`. – kiran Biradar Nov 06 '19 at 12:04
  • 3
    Congratulations! You have discovered **undefined behaviour**. – haccks Nov 06 '19 at 12:05
  • What does that mean? – Muhammad Usman Nov 06 '19 at 12:05
  • @MuhammadUsman What were you expecting? – kiran Biradar Nov 06 '19 at 12:07
  • I am using online ide from repl.it. Thought that might be relevant. – Muhammad Usman Nov 06 '19 at 12:07
  • [No out of bounds error](https://stackoverflow.com/questions/9137157/no-out-of-bounds-error) [What happens if I try to access memory beyond a malloc()'d region?](https://stackoverflow.com/questions/1655971/what-happens-if-i-try-to-access-memory-beyond-a-mallocd-region) – KamilCuk Nov 06 '19 at 12:08
  • It's not relevant which IDE you are using. You are allocating 20 bytes, and then writing those 20 bytes + 10 extra bytes after allocated memory block, which will lead to undefined behavior. – Andrejs Cainikovs Nov 06 '19 at 12:09
  • @AndrejsCainikovs I suppose. Then is there even a point of the `x` in `char p[x];` or is it just stupid? – Muhammad Usman Nov 06 '19 at 12:16
  • @AndrejsCainikovs or does it behave correctly with `char p[x];` but not `char* p[x];`? – Muhammad Usman Nov 06 '19 at 12:17
  • Answers: 1. Please read about differences in memory allocation on stack and heap. 2. `char* p[x];` will allocate array of pointers. – Andrejs Cainikovs Nov 06 '19 at 12:29
  • @AndrejsCainikovs ok thanks I just got a little confused for a while is all, but before I can proceed I need to know if there was anything else wrong with my code. Have I used pointer variables and malloc() correctly? – Muhammad Usman Nov 06 '19 at 12:30
  • You used the memory allocation and pointers correctly, but: 1) malloc might return NULL if failed to allocate memory; 2) do not write out of allocated memory bounds; 3) always free allocated memory – Andrejs Cainikovs Nov 06 '19 at 12:38

1 Answers1

1

The comments tell you what is wrong, but I will consolidate those comments.

You allocate storage with malloc. This returns you the address of where you may store your data. However, neither C, nor malloc or the heap will check if you store only in the area given to you. If you write beyond the area allocated, you are writing in an area that is "not yours". This can lead to various types of undefined behavior.

Some memory managers will intercept your attempt and will abort your program. Other memory managers don't do that, but since you write to an area that is not yours, you may be overwriting data from the memory manager and any next attempt to allocate memory may fail because the memory manager's data is corrupt. Or you are overwriting memory that belongs to someone else.

So the fact that it seems you can write more than you allocated, does not mean your program is correct. In fact, it is hopelesly wrong and will lead to an error somewhere else. So your program could make for example invalid calculations and your airplane crashes... This is called undefined behavior and you as a programmer must take care you always allocate what you need and that you never go out of the bounds of what you allocated.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • I am sorry I don't have enough reputation to upvote. This is what I needed -> `So the fact that it seems you can write more than you allocated, does not mean your program is correct. In fact, it is hopelesly wrong and will lead to an error somewhere else.` – Muhammad Usman Nov 06 '19 at 12:23
  • May I just ask one more question (answer in comments)? Say I had never attempted to write beyond the area allocated in the first place. Have I used pointers and malloc() correctly here? – Muhammad Usman Nov 06 '19 at 12:26
  • Yes, you have. To be completely correct, you should free the memory before you end the program: `free(foo);` After you freed the memory, you may no longer use it (it isn't yours anymore). – Paul Ogilvie Nov 06 '19 at 12:30