Why is the malloc argument needed in C?

Question:

I started learning C from one book. There was an example like this:

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

int main(int argc, char const *argv[]){
    char *char_ptr;
    int *int_ptr;
    int mem_size;

    mem_size = 1;
    printf("\t[+] allocation %d bytes of memory on the heap for char_ptr\n", mem_size);
    char_ptr = (char *) malloc(mem_size);
    strcpy(char_ptr, "This is memory is located on the heap");
    printf("char_ptr (%p) --> '%s'\n",char_ptr,char_ptr);
}

Here I allocate 1 byte for the heap. Then I write down the text "This is memory is located on the heap" there. I thought there would be an error, because the text needs more than 1 byte. But I got a result like this:

[+] allocation 1 bytes of memory on the heap for char_ptr
char_ptr (0x55e250f6c670) --> 'This is memory is located on the heap'

From this example, I have one conclusion: Did the heap grow on its own? But if it was increasing the size, then why is the malloc () argument needed? Can you explain why this works?

Answer:

The code is wrong. No, the allocated block of memory has not grown. You write outside of block boundaries, so you have undefined behavior in your code. Error in such cases is not guaranteed.


More details:

I thought there would be a mistake

For an error to occur, the compiler must generate some code that checks the bounds of the allocated memory block.

In general, this is not a trivial task. In addition, programs with such checks would run slower.

Therefore compilers (with default settings) usually do not add such checks.

In turn, the standard does not require these checks. Instead, it says that going outside the bounds of an array or allocated block of memory causes undefined behavior . This means that the program can behave as you like.

Usually, in situations like yours, the program either modifies the values ​​of unbound but adjacent variables in memory; either crashes immediately; or crashes after some time in some other place; or nothing happens at all.

Some compilers have settings that -fsanitize=address protection against such errors ( -fsanitize=address for GCC, etc.).

Scroll to Top