#include <stdio.h>
void removeString(char text[], int beg, int remove)
{
int index;
for(index = beg; text[index + remove] != '\0'; index++)
text[index] = text[index + remove];
text[index] = '\0';
}
int main(void)
{
char text [] = "the wrong son";
removeString(text, 3, 40);
printf("%s\n", text);
}
Asked
Active
Viewed 39 times
1

R Sahu
- 204,454
- 14
- 159
- 270

Hani Damlaj
- 11
- 1
-
Why should it? Who told you it would? – kaylum Oct 10 '16 at 02:28
-
2Undefined behavior is not required to produce errors. It is, well, undefined. – Sergey Kalinichenko Oct 10 '16 at 02:28
-
You could rewrite the method as `strcpy(text+beg, text+beg+remove);` – user207421 Oct 10 '16 at 03:46
1 Answers
2
C does not have any bounds checking. You can refer to anything you like and it's up to you to make sure it makes sense.
Depending on the platform and other factors, you can get garbage, memory exceptions or any other random crashes as your code corrupts memory and the stack.

LoztInSpace
- 5,584
- 1
- 15
- 27
-
The code works and produces the result I want. It does not return garbage values. – Hani Damlaj Oct 10 '16 at 02:38
-
-
That's what I'm thinking, is there a reason as to why it is a readable zero? – Hani Damlaj Oct 10 '16 at 02:45
-
Could be anything. There might be another global variable. As a string constant, `text` could be bundled up with any other strings from error messages, library constants etc. who knows. That's the nature of C. Sometimes wrong will work until something apparently unrelated changes. I'd not rely on it that's for sure! – LoztInSpace Oct 10 '16 at 02:58