0

I am at a total loss with this one. I can't figure out why this isn't working. Simple character array with a NULL terminator - except that when I output it, it doesn't terminate!

int file_create(const char *path) {
    //trying to trap situations where the path starts with /.goutputstream
    char path_left_15[16];
    strncpy(path_left_15, path, 15);
    printf("%d\n", strlen("/.goutputstream")+1);
    path_left_15[strlen("/.goutputstream")+1] = '\0'; 
    printf("%d\n", strlen(path_left_15));
    printf("path_left_15: %s\n", path_left_15);
    //continue on...
}

This is my output:

> 16 

> 16 

>/.goutputstream\B7<random memory stuff>

I can't figure out why this isn't terminating correctly. I've tried making the array longer, but I get the same result every time. I'm losing my mind!

Anyone see it? Thanks.

AndroidDev
  • 20,466
  • 42
  • 148
  • 239

2 Answers2

2

Your array only has 16 elements, bu you're trying to write to the 17th. So that's undefined behaviour.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

You are out of bound from the array. Instead of path_left_15[strlen("/.goutputstream")+1] = '\0'; try path_left_15[15] = '\0';

You will truncate your string but will be safe when printing.

Amadeus
  • 10,199
  • 3
  • 25
  • 31
  • I knew this would end with me realizing how dumb I can be. Another example of forgetting when to count from 0 and when to start from 1. Thanks! – AndroidDev Apr 20 '13 at 00:34
  • BTW, this doesn't truncate my string. By adding the terminator to path_left_15[15], that's the 16 position of my array - exactly where I want it to be. Thanks again. – AndroidDev Apr 20 '13 at 00:35