-1

I'm working on a project in which i need to create a string of arbitrary length and set all the characters to a specific character.

Example of setting bytes:

char str[i];
memset(str, '*', i);
str[i] = '\0';

This seems to work so far, however when I change the last line to str[i + 1] = '\0';, my output is being shortened by one.

Can anyone explain why this is happening?

  • 6
    `str[i + 1]` isn’t in bounds. `str[i]` isn’t either. You declared the array as having `i` elements with indexes from `0` to `i - 1` inclusive. – Ry- Oct 15 '17 at 08:17
  • Please provide a [mcve]. – rustyx Oct 15 '17 at 08:25
  • Please note that doing `int i = 42; char str[i];` makes use of the language element called "Variable Length Arrays", which is available form C99 on only, and had become *optional* with C11. (Also VLAs are not supported by C++ at all), – alk Oct 15 '17 at 09:09
  • if you need "a string of arbitrary length" then use `malloc`, don't use [VLA](http://en.cppreference.com/w/c/language/array#Variable-length_arrays) which is very dangerous unless you can be sure that the string is always small enough to not result in stack overflow – phuclv Oct 15 '17 at 11:16

2 Answers2

1
str[i] = '\0';

and

str[i + 1] = '\0';

are undefined behaviour because C language does not checking array bound.

C11 standard :

J.2 Undefined behavor

  • An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).
msc
  • 33,420
  • 29
  • 119
  • 214
1

With str[i] and str[i + 1] you are accessing outside the bounds of str. This is undefined behaviour.

If you need i length of data (excluding the terminating null byte), your array str has to have space for i + 1 elements in order to accommodate the null terminator.

On the other hand, if you are not using str as a C-string (e.g., using any of the standard C library functions that expect a null terminated strings), then you don't need to null terminate it at all.

P.P
  • 117,907
  • 20
  • 175
  • 238