2

I was implementing a program related to the use of dynamic allocation in C.
Testing the same piece of code on Visual Studio 2017 and on other IDEs (Dev C ++, Codeblocks, etc.) I have different behaviors:

size_t newDim = 9;
char *p = malloc((newDim + 1) * sizeof(char));
p[newDim] = '\0';
printf("%d\n", strlen(p));

The output of printf() on Visual studio is: 9
other IDEs: 3 sometimes 4.
But when I fill the array with dim-1 characters, the same printf() produces a correct output on the other IDEs. I think that the different compilers have a different way of managing the allocated memory, could someone explain the problem in more detail?
Thank you

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
arst3k
  • 976
  • 2
  • 8
  • 18
  • you need `calloc` if you need zero-init. And if you think it's zero, why nul-terminating? – Jean-François Fabre Jan 09 '18 at 21:48
  • Should be completely random, but at most 9, because you have not put anything into the memory you allocated, so it's contents are undetermined. – Lee Daniel Crocker Jan 09 '18 at 21:49
  • @LeeDanielCrocker but why Visual studio behaves in a different why compared to the other compilers? So should I initialize the memory, add the terminating zero and then use the strlen () function? – arst3k Jan 09 '18 at 21:54
  • @arst3k What are you even trying to do here? What is the point to measure an uninitialized string? – Eugene Sh. Jan 09 '18 at 21:55
  • Contents of memory from malloc() is *undefined*. There's no reason to think it should be the same from one compiler to the next, or even one run to the next on the same machine. Malloc just grabs whatever memory is available and assigns it to you. Whatever it might have had in it from previous use is still there. Why would C bother putting anything into it? That's just a waste of time. – Lee Daniel Crocker Jan 09 '18 at 21:59
  • @LeeDanielCrocker Well, `calloc` is doing it. – Eugene Sh. Jan 09 '18 at 22:00
  • Calloc is *defined* to do it. That's its job. – Lee Daniel Crocker Jan 09 '18 at 22:00
  • *The output of printf() on Visual studio is: `9`* Change from debug to release (or the other way - or any other version of the MSVC run time library that you have available) and see what happens... – Andrew Henle Jan 09 '18 at 22:07
  • `char *p = malloc((newDim + 1) * sizeof(char));` --> `char *p = calloc(newDim + 1u, sizeof *p);` and let `calloc()` set all to 0. – chux - Reinstate Monica Jan 09 '18 at 22:37

1 Answers1

5

malloc is not initializing the memory allocated, so the allocated space might have zeros in arbitrary places giving different string lengths.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61