-1

I am compiling and running this code:

// hello, world!, without printf

#include <stdio.h>
#include <string.h>

char a[7] = "hello, ";
char b[7] = "world!\n";

void putCharArray(char *ray) {
  for (int i = 0 ; i < strlen(ray) ; i++ ) 
    { putchar(ray[i]);  }    
}

void main() {
    putCharArray(a);
}

on Ubuntu 20 using gcc. When it runs it outputs:

hello, world!

So it seem like it runs past the 'a' array and right into the 'b' array.

Would someone please explain how that is? Please and thank you.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 3
    *Undefined behavior*. Your array `a` is too small to hold the null-terminator, so calling `strlen` on it invokes UB – UnholySheep Jul 23 '20 at 17:42
  • For the fun of it, put something in between the line of a and b say int i = 34;. – stackoverblown Jul 23 '20 at 17:44
  • FWIW your loop is doing double work traversing the string (or even quadratic - if the code is poorly optimized). Instead of using `strlen` you should print as long as you don't encounter the terminator `\0` (because this is what `strlen` does). And this way you will also see your problem more clearly. – Eugene Sh. Jul 23 '20 at 19:23

1 Answers1

3

The both character arrays

char a[7] = "hello, ";
char b[7] = "world!\n";

do not contain strings because the sizes of the arrays are not enough large to include as an initializer the terminating zero character '\0'. So calling the function strlen invokes undefined behavior.

You should declare the arrays like

char a[] = "hello, ";
char b[] = "world!\n";

or like (specifying the sizes of the arrays at least not less than 8)

char a[8] = "hello, ";
char b[8] = "world!\n";

Or you could change the function the following way

void putCharArray( const char *ray, size_t n ) {
  for (size_t i = 0 ; i < n ; i++ ) 
    { putchar(ray[i]);  }    
}

and call it like

putCharArray( a, sizeof( a ) );

Pay attention to that according to the C Standard the function main without parameters shall be declared like

int main( void )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335