-2

This C-code compiles without any errors/warning. When I run this program, I can enter more than 16 chars and it will gladly echo all of my chars.

Forever?

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

#define BUFFER_SIZE 16
int main() {           
    char* buffer = malloc(BUFFER_SIZE);
    while (1) { 
        bzero(buffer, BUFFER_SIZE); 
        scanf("%s", buffer);    
        puts(buffer); // echo           
    }
    free(buffer);
   return 1;
}

(Compile with: "gcc bufferoverflow.c -o buffer -Wall")

Why is this working? When will it crash?

user1511417
  • 1,880
  • 3
  • 20
  • 41
  • 2
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – too honest for this site Oct 29 '15 at 20:20
  • 1
    Maybe you should meditate about: "Is it really *that* bad to ask why something **is** working?" – user1511417 Oct 29 '15 at 20:25
  • 3
    `C`: Coding without training wheels. – chux - Reinstate Monica Oct 29 '15 at 20:27
  • 2
    It is working because malloc is almost certainly allocating more memory than you requested to prevent fragmentation. –  Oct 29 '15 at 20:31
  • @DavidCullen: To repeat an unjustified deleted (mod gone trigger-happy?) comment: It does **not** work once you invoke/rely on UB. You just might not notice that. – too honest for this site Oct 29 '15 at 20:48

1 Answers1

4

Basically, you've encountered "undefined behaviour".

You can read more than you allocated because scanf() doesn't know how much you allocated. To avoid that, use fgets() from stdin and then sscanf().

The most common behaviour in such a case is that scanf just keeps writing chars to the memory. Not forever, of course. Something will stop it, if nothing else, it will run out "past the end of memory" at some point and, on most modern systems, an unhandled exception will occur and your program will crash. On embedded systems you might just halt the processor.

It is working because nothing significant is past the buffer you allocated, so overwriting it doesn't produce adverse effects. That doesn't have to be, of course, and you may touch something sensible and crash, or worse, change behaviour of some part of your program/system without crashing.

srdjan.veljkovic
  • 2,468
  • 16
  • 24