Question: This is some working code that I wrote to call a JSON file and cache it on my servers. 

I'm calling the cached file. If the file exists I use json\_decode on it. If the file doesn't exist I then call the JSON and decode that. Then after calling the JSON url, I write the contents to the cached file url.

```
$cache = @file_get_contents('cache/'.$filename.'.txt');

 //check to see if file exists:
if (strlen($cache)<1) {

    // file is empty
    echo '<notcached />';
    $JSON1= @file_get_contents($url);

    $JSON_Data1 = json_decode($JSON1);

    $myfile = fopen('cache/'.$filename.'.txt', "w");
    $put = file_put_contents('cache/'.$filename.'.txt', ($JSON1));

} else {

    //if file doesn't exist:
    $JSON_Data1 = json_decode($cache);
    echo '<cached />';
}

```

Instead of only using `if (strlen($cache)<1) {`, is there a way that I can check the age of the $filename.txt and if it's older than 30 days grab the JSON url in the else statement?

Answer: 
The behaviour of `atoi(test);` is *undefined*. The parameter `test` (once decayed to a pointer type) must point to a NUL-terminated array of `char`. Yours isn't.

The solution is trivial here, write

```
char test[9] = {0};

```

instead to force the inclusion of a NUL-terminator . But do note that the resulting number is of the order of 10 million; perhaps therefore too big for an `int`. Use a `long` instead to be sure, along with `atol` instead of `atoi`. If you want the string to be parsed as binary, then use `strtol` passing a radix of 2.
As already mentioned in other answers, the core problem is that you don't null terminate the string. But there's various other bad practice in this program:

* [The atoi() family of functions should never be used for any purpose](https://stackoverflow.com/a/46563868/584518), since they have no error handling.
* Never use bitwise operators on signed numbers or signed integer constants. `1` is a signed type, for example. Code like `1<<15` will invoke undefined behavior on 8 and 16 bit CPUs.

A corrected program might look like this:

```
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
  unsigned int c = 100;

  char test[8+1];

  for(size_t i=0; i<8; i++)
  {
    test[i] = c & (1u<<(8-1-i)) ? '1' : '0';
  }
  test[8] = '\0';

  int j = (int)strtol(test, NULL, 10);
  printf("%.8d\n", j);

  return 0;
}

```

Or if you live and breathe C language operator precedence (major nerd warning), you could be cocky and just write `test[i] = c & 1u << 8-1-i ? '1' : '0';`. As the operator precedence here is: `-`, `<<`, `&`, `?:`, `=`.