0

I would expect to see compile errors from this code and perhaps an error when the executable is run. From my understanding, if a pointer is assigned and exists in the heap, and malloc reserves space for the pointer, if what is placed at the pointer is too large, it should start to override code space. However, this runs without issue on Linux 64 bit Ubuntu 14.04.

In this example, I am reserving 5 bytes initially but putting 21 bytes (\0 would be byte 21?) at that memory address. The program runs without issue and the compiler throws no error.

I compiled using the command: "gcc -Wextra -pedantic test.c -o test"

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

int main()
{
   char *str;

   /* Initial memory allocation */
   str = malloc(5);
   strcpy(str, "12345678901234567890");
   printf("String = %s,  Address = %p\n", str, str);

   /* Reallocating memory */
   str = realloc(str, 26);
   strcat(str, "12345");
   printf("String = %s,  Address = %p\n", str, str);

   free(str);
   return(0);
}
  • 4
    You have undefined behaviour in your code. The reason that it worked perfectly is by pure luck. UB means anything can happen. – Spikatrix Nov 23 '14 at 05:40

2 Answers2

0

Malloc will return a block larger than 5 bytes. I am guessing it changes on implementation, but quick google search says 16 bytes.

I would not expect the compiler to produce a compilation error (though maybe a warning?)

laughingpine
  • 1,039
  • 14
  • 20
0

In C, it does not give an error or warning if a buffer overflow occurs without adding some sort of bounds checking. Since you are reading and writing to invalid memory, the output of your code is undefined. Sometimes you might be fortunate and get a segmentation fault and you know right away you have an access violation.

You can see that you have invalid reads and writes by running valgrind ./test. I encourage you to familiarize yourself with valgrind as a debugging tool for detecting memory management bugs such as the one you introduced in your code.

David Pisani
  • 181
  • 1
  • 7