1

This function:

static int function_name(lua_State *L) {
  const char* str = lua_tostring(L, 1);
  const char* substr = lua_tostring(L, 2); // passing "how" results in "how-" ???

  char *pch = strstr(str, substr);

  if (pch != NULL)
    lua_pushinteger(L, pch - str);
  else
    lua_pushnil(L);

  return 1;
}

Invoking the function (i.e, function_name("hello how world", "how") produces this result. Why would lua_tostring return such an obfuscated result? This issue only occurs when I pass a string equal to the length of the substring I want to match to. For example

"hello how world", "hell" -> works fine
"hello how world", "hello" -> fails, thinks "hello-" is passed. 
"hello how world", "ho" -> works fine
"hello how world", "how" -> fails, thinks "how-" is passed.

I'm printing substr immediately after I pull it from the stack to observe results. I don't believe any middle-men could mess it up.

Nifim
  • 4,758
  • 2
  • 12
  • 31
wellinthatcase
  • 120
  • 2
  • 8
  • Which Lua version? – Oka Mar 10 '22 at 05:15
  • @Oka 5.4 7morechar – wellinthatcase Mar 10 '22 at 05:15
  • 2
    I could not replicate this issue on Lua 5.4.4. Apart from maybe adding some error checking to avoid segfaulting, this function seems fine to me. You might need to update the question with more specifics about your build environment (Lua patch version, OS, compiler version, compilation flags, etc.), and a more complete [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – Oka Mar 10 '22 at 05:40
  • I'm using the same patch version, so I'm stubbed I suppose. – wellinthatcase Mar 10 '22 at 05:42
  • Have you included when compiling this code? – lhf Mar 10 '22 at 10:24

1 Answers1

0

Using PUC Lua version lua-5.4.0 compiled for X86-64 with MinGW, I registered the C function function_name to the Lua function TEST.

print(TEST("hello how world", "hell"))
print(TEST("hello how world", "hello")) 
print(TEST("hello how world", "ho"))
print(TEST("hello how world", "how"))

The results seems correct:

0
0
6
6

If you are facing strange data corruption during the runtime of your program, you might have an pointer issue in some other places of your program, possibility in another thread.

Robert
  • 2,711
  • 7
  • 15
  • Agreed on the later statement. I did more debugging later the night and discovered one of my earlier C functions seem to mess something up, where (i.e) the first parameter of function1 persists as the first parameter in function2 regardless of what I pass. It's strange because I don't do anything fishy there besides copy a string off the stack into a buffer. I'll have to rewrite it and test each line to see where it's going wrong. – wellinthatcase Mar 10 '22 at 14:22