I am trying to understand buffer overread in my course in school. This code is an example from one of the lectures where buffer overread can be a problem. However, I do not understand how buffer overread can occur in this code.

In my knowledge, b is assigned char of length 4 (0 to 3) but the string is only of length 3 (0 to 2). The last char is then assigned after. b[3] = "d";. How is that buffer overread? It is setting the char "d" to the last allocated element in the array. For me, buffer overread is if someone tried to read b[5], which is not in the boundaries of the array, but b[3] is.

Can someone please explain?

int main()
    char b[4] = "abc";
    b[3] = "d";
    printf("b: %s \n", b);

    return 0;

1 Answer 1


Strings in C are null-terminated, so it should end on \0. When b[3] was changed, you removed the \0 and now the string is unbounded. Running it will let printf read everything until it gets the first \0, terminating the string.

Why this is an issue? It will print memory that it wasn't supposed to print. That's the issue that caused Heartbleed: you were able to read more data than you were supposed to read.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .