Home > Software design >  Substracting char* in C
Substracting char* in C

Time:06-10

I am reading through this blog post: https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times-by-70/

I am confused on how:

size_t len = char* end - char* str

If I am correct, strings in C are represented as arrays and Cstrings have pointers to the first element of that array. So is that above line playing with array subscripts?

He posts these lines:

size_t strlen_cacher(char* str)
{
  static char* start;
  static char* end;
  size_t len;
  const size_t cap = 20000;

  // if we have a "cached" string and current pointer is within it
  if (start && str >= start && str <= end) {
    // calculate the new strlen
    len = end - str;

    // if we're near the end, unload self
    // we don't want to mess something else up
    if (len < cap / 2)
      MH_DisableHook((LPVOID)strlen_addr);

    // super-fast return!
    return len;
  }

  // count the actual length
  // we need at least one measurement of the large JSON
  // or normal strlen for other strings
  len = builtin_strlen(str);

  // if it was the really long string
  // save it's start and end addresses
  if (len > cap) {
    start = str;
    end = str   len;
  }

  // slow, boring return
  return len;
}

CodePudding user response:

if (start && str >= start && str <= end) { is undefined behavior (UB) unless start and end are within the same object that str points to.

strlen_cacher("Hello");
strlen_cacher("World"); // UB

In C it is UB to compare with >, >=, <=, < unrelated pointers.


"He posts these lines:" --> Take care when importing other's code.

CodePudding user response:

Lets assume the code is correct and start is a pointer to the first element of the string, and end is pointer to the string nul terminator:

#include <stdio.h>

int main() {

    char str[] = "hello";

    char *start = str;

    char *end = str   5; // will point to the last element of str, the nul byte

    printf("%td", end - start); // 5

}

This is simple pointer arithmetic.

  • Related