0

I have this simple program in which I initialize a string with "HELLO". I need the output to be printed as HLOEL, i.e) all the even indexes (0,2,4) followed by the odd ones (1,2). I could not infer what's wrong with my code, but it yields "HLOELHLO" instead of "HLOEL". Could someone explain what is happening here?

#include <stdio.h>

int main() {
    int i,loPos=0,hiPos=0;
    char *str="HELLO";
    char lo[2];
    char hi[3];
    for(i=0;i<5;i++)
    {
        if(i%2==0)
        {
            hi[hiPos++]=str[i];
        }
        else
        {
            lo[loPos++]=str[i];
        }
    }
    printf("%s%s",hi,lo);
    return 0;
}

Thanks in Advance!

  • 2
    Common error. C strings need to be NUL terminated. Your arrays are not NUL terminated. Increase size of each array by one and store `\0` as the last element. – kaylum Jul 26 '22 at 06:33
  • Failed to notice that! Thanks a lot, It helped! @kaylum – Vikneysh Raj G G A Jul 26 '22 at 06:35
  • 1
    Also don't try to save a few bytes of space with strings, unless you're absolutely 100% certain of their length (*including* the null terminator). Define your arrays with a size that is guaranteed to be big enough, plus some margin, to fit the strings you want to put in the (like in your case, `char lo[16] = "";`, which will incidentally make sure it's zero-initialized (zero is the same as the string null terminator)). – Some programmer dude Jul 26 '22 at 06:39
  • 1
    On another note, literal strings like `"HELLO"` are really *read only* arrays of characters (including the null terminator). Because they are read only (they are not allowed to be modified) it's recommended to use `const char *` for pointers to them. – Some programmer dude Jul 26 '22 at 06:40

2 Answers2

1

After the for loop, you need to put string terminating 0 bytes to the new strings, and also make sure they habe room for it:

char lo[2+1];
char hi[3+1];

for(...) {
}
hi[hiPos] = '\0';
Lo[loPos] = '\0';

Otherwise any string functions will have buffer overflow, causing undefined behavior. Generally they will keep reading bytes until by chance they encounter byte with value 0. But as always with undefined behavior, even this can cause your program to do anything.

hyde
  • 60,639
  • 21
  • 115
  • 176
1

because C style string need extra one char '\0' as its end. With your code, the memory layout around two arrays maybe looks like:

lo[0], lo[1], hi[0], hi[1], hi[2], something else equal 0,

printf stops when it meets a '\0'

you should declare arrays as:

char lo[3];
char hi[4];
lo[2] = '\0';
hi[3] = '\0';
g11de
  • 74
  • 5