Why does this work? Character pointer in C

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

int main()
{
    char* s = (char*)malloc(sizeof(char) * 3); //I allocate memory for 3 chars
    s[0] = 'a';
    s[1] = 'b';
    s[2] = '\0';
    s[3] = 'd'; //This shouldn't work

    std::cout << s[3] << std::endl; //It prints out d, why?

    free(s);        
    return 0;
}

Why am I allowed to write s [3]?

+3
source share
8 answers

Usually the malloc function allocates a certain minimum number of bytes, for example 16, even if you ask to select only one (or 3 as in your example) byte (s).

However, you should not rely on such a function function. An implementation is defined as malloc allocates memory. So your code has undefined behavior.

+5
source

This is called undefined behavior.

The compiler does not prevent you from committing illegal actions; however, compiled code may not do what you expect.

+6
source

s [100], . , , , .

, C/++ , . , , . , , Valgrind, cppcheck , . , cppcheck , valgrind .

+2

, . , , .

d, , . undefined.

+1

s [3]?

.

undefined, , .

+1

s[3] = 'd'; undefined. , -, , .

+1

. , . , . undefined.

+1

, ...

, C: C , , . - . ( ), , .

, . , C , , , . , malloc - , . , , . : malloc ( ) ( ).

+1

All Articles