1

While writing the following code I should get an error. The array size is given as zero(which I suppose is illegal) and furthermore sprintf is printing "abc" to a which has not been allocated any memory but I am getting the output as "abc". I cant understand why?

#include<stdio.h>
#include<string.h>
int main()
  {
    char a[0];
    sprintf(a,"%s","abc");
    printf("%s\n",a);
    return 0;
  }

I am getting the correct output when i am giving the array size to be 1,2,3 which should not be the case while it is giving segmentation fault for explicitly using a as a pointer ,i.e, using char *a(which is expected). Can somebody explain the internal working?

user2179293
  • 425
  • 9
  • 22
  • It may be helpful - http://stackoverflow.com/questions/14565778/c-how-protect-dynamic-char-before-overwritte-by-second-dynamic-char – Jan Czarny Mar 17 '13 at 13:25
  • when running `sprintf(char *string,const char *,...)` the pointer to the end of `string` is always defined as `(char *)-1`,or using `vsnprintf(buf,SIZE_MAX,format, arg);`apparently,they are not safe. – yuan Mar 17 '13 at 15:52
  • You're most likely overwriting allocated memory in the stack, which is why you get no segfault. If it overwrites data that isn't needed it can seem that everything is ok. – teppic Mar 17 '13 at 17:23

1 Answers1

4

No, there's no reasonable explanation. By using an array which is smaller than the string to be printed, your program invokes undefined behavior. That means that literally anything can happen, including the fact that everything seems to be working fine. Undefined behavior doesn't mean that the program must crash, it means that it can crash.