Jack Garbiec Jack Garbiec - 3 months ago 24
C Question

I can access array element [32] when i only allocate [30].(C)

I don't know the inner workings of c so this is quite confusing. I've been playing with arrays and pointers and a lot of weird stuff is going on, I hope someone can point me to a resource that explains how this stuff works under the hood. I was looking at the c programming reference but could not find answers.
So here is a piece of code:

#include <stdio.h>
#include <stdlib.h>
#define PATH "/home/jack/Desktop/Cpractice/hangman.txt"

int main()
FILE *file;
file = fopen(PATH, "r");
int c;
int size;
//char *word = (char *)malloc(0);
char word[30];
//printf("\tSize: %lu\n",sizeof(char));
int i =0;
c = getc(file);
if(c == EOF)
word[i] = c;
printf("%s\n", word);
printf("I: %i\n", i);

return 0;

I've got 32 chars in a file, the word array accepts them without any errors, even though they exceed the size, printing confirms it, all chars get printed.
Even running it in gdb, I can "print word[31]". So my question is, why is the array allocating more than 30 chars(30 bytes?) of memory, can you please explain or point me to a book or an article that explains what happens under the hood when you declare char[30]?


It's my first comment so i'll try to be as clear as possible.

To be quite short, the memory in C language is a bit special, but not complicated until you dig a bit the subject.

The malloc function (dynamic allocation) and static allocation uses a system call : sbrk (I advise you to read the man to understand what exactly the function does) https://linux.die.net/man/2/sbrk

Your question is "why can I read tab[size + 1]", it's juste because the memory given to your array isn't only size, in fact, if there is free space after, you'll be able to access it, but BE CAREFUL because this will probably lead to some errors in your program after some time...

Errors are possible because if you declare another array after this one, let's say an array of 6 chars named tab2, and in memory this array starts right after the other one, when you'll try to modify tab1[size + 1] you'll got a segmentation fault because the space is used by tab2 (even reading tab1[size + 1] could lead to a segmentation fault, but sometimes, computer are too kind and let you do that)

Wathever, I hope it's quite clear, if it isn't, don't hesitate to ask me questions !