lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> On Apr 22, 2015, at 12:23 PM, basiliscos@openmailbox.org wrote:
> 
> Hello dear lua community,
> 
> 
> int lua_my_fun(lua_State *L) {
>  return 0;
> }
> 
> static char* script;
> 
> static int load_script(char* script_path) {
>  struct stat script_stat;
>  int result;
>  FILE *script_file;
>  size_t records_read;
> 
>  result = stat(script_path, &script_stat);
>  if (result) {
>    perror("error get script stats");
>    return -1;
>  }
> 
>  script = malloc(script_stat.st_size);
>  if (!script) {
>    fprintf(stderr, "cannot allocate %ld bytes for script\n", script_stat.st_size);
>    return -1;
>  }
> 
>  script_file = fopen(script_path, "r");
>  if (!script_file) {
>    perror("cannot open script file");
>    return -1;
>  }
> 
>  records_read = fread(script, script_stat.st_size, 1, script_file);
>  if (records_read != 1) {
>    fprintf(stderr, "error reading script %s\n", script_path);
>    return -1;
>  }
> 
>  /* success */
>  return 0;
> }
> 

Doesn’t look like you are adding an EOS ‘\0’ terminator at the end of the loaded script (fread doesnt do this), so Lua is running off the end of the script and hitting garbage. Allocate one more byte in the malloc() and make sure you set the last byte of the memory block to 0 to terminate the string.

—Tim