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

int main()
{
    char* id;                                          
    int n;
    printf("enter the no of char you want\n");
    scanf("%d", &n);
    id = (char*)malloc((n+1)*sizeof(char));
    printf("enter the id\n");
    scanf("%s", id);
    printf("%s\n", id);
}

I am not able to understand this. I allocate memory of my desired length. Then I take a string as input (which otherwise not allowed) how is this possible and I am able to write more than the allocated chars and it is still printing.

  • 2
    `malloc` does not guarantee to *exactly* allocate the number of bytes requested, it might allocate even more (e. g. up to the next power of two). Even if it reserves exactly, OS usually assigns memory to processes in form of memory 'pages' – as long as you stay within such page, you might not suffer a segmentation fault. But you might overwrite other parts of memory, leading to very difficult to find errors (maybe a crash at a seemingly totally unrelated part of your code). In any case, writing beyond the allocated array's bounds remains *undefined behaviour*. – Aconcagua Jun 13 '21 at 17:01
  • `char format[16]; sprintf(format, "%%%ds", n); scanf(format, id);` would be a safe equivalent way not to write beyond the array bounds, by the way. If you want to input whitespace as well until first newline, have a look at [`fgets`](https://en.cppreference.com/w/c/io/fgets). – Aconcagua Jun 13 '21 at 17:09
  • Please see [Why char pointer saving data more than allocated memory in C?](https://stackoverflow.com/questions/58620242/why-char-pointer-saving-data-more-than-allocated-memory-in-c) – Weather Vane Jun 13 '21 at 17:18
  • Note that C does not employ memory police. It goes wrong when you *break* soemthing, and if the thing you broke was benign, you'll "get away with it". Like jumping a red light does not guarantee a traffic collision. That will be next time when you think it was OK. – Weather Vane Jun 13 '21 at 17:20

0 Answers0