1

I stumbled upon a "weird" behavior of malloc function. I'm looking for a way to allocate memory based on input from a user. I'm allocating one byte of memory, so as I understand, I'm creating a place for just one char variable, but when my input is a message with even over 100 characters, it prints out exactly the input. How is it possible that all of my input can fit in just one byte?

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


int main(int argc, char const *argv[])
{
    char *nam = malloc(sizeof(char));

    printf("Write your name:\n");
    scanf("%s", nam);

    printf("Your name is: %s", nam);

    return 0;
}
cover
  • 57
  • 1
  • 1
  • 8
  • 1
    You are not creating a place for just one `char` object. You are reserving a byte that is already there, among millions of other bytes that are already there. Then you used more than you reserved. Same thing as at a bowling alley where you ask for one lane and then bowl in the neighboring lanes too. Maybe the staff will not notice at first. Maybe they will. (To be technical, the memory might not already be there; the virtual memory might not be mapped yet, until `malloc` asks the operating system for it. But then it gets more than the one byte you asked for; mapping is done in chunks.) – Eric Postpischil Jun 13 '23 at 14:30
  • 1
    You get Undefined Behaviour (UB), "anything" can happen, including does exactly what you would expect when UB wouldn't occur. – 12431234123412341234123 Jun 13 '23 at 14:32
  • Try to free the memory again, do the same happen? Try to `(m)alloc()` objects before and after you alloc it for `nam` set them to specific values and then write over the buffer and observe if the objects before and/or after change, try to free it. You could also try valgrind to better understand what happens. – 12431234123412341234123 Jun 13 '23 at 14:35
  • 1
    @cover, BTW `scanf("%s", nam);` is not only bad as it has no _width_ limit, but since names, even a single name, can have spaces in them, `"%s"` will not read all the name. Research `fgets()` and stop using `scanf()` until you know why it is bad. – chux - Reinstate Monica Jun 13 '23 at 14:44

0 Answers0