Welcome to the Builder Academy

Question Bug (I think) in magic.c:mag_affects()

More
26 Feb 2022 02:27 #10024 by jandulio
I've been in C# land for many years now, but I think there are pointer issues in magic.c:mag_affects() line ~308 (tbamud-2020)

These pointers are never malloc'd/allocated, so settings strings to them is a bad idea.  Please correct me if I'm wrong.
  // pointers declared
  const char *to_vict = NULL, *to_room = NULL;
  ...
  // pointers used
  to_room = "$n seems to be blinded!";
  to_vict = "You have been blinded!";


I *think* those variables should be used like this:
  // char arrays initialized
  char to_vict[128] = { 0 };
  char to_room[128] = { 0 };

  // char arrays used
  strcpy(to_room, "$n seems to be blinded!");
  strcpy(to_vict, "You have been blinded!");

Please let me know if I'm off here because I could be missing something.

Please Log in or Create an account to join the conversation.

More
26 Feb 2022 14:22 #10025 by thomas
I think it's your C# training causing you to see ghosts ;)

A 'const char *' pointer points to a char array defined in the executable. Pointing to the constant string "$n seems to be blinded!" is allowed without memory allocation because the string is stored when compiling in a part of the binary along with other strings. Typically, this loaded as a part of the code which means it will typically reside in read-only memory.

Your suggested change would use a specific sized buffer and copy from the constant string pool. This is an extra, unneeded step in C, as it is perfectly reasonable for a string to reside in the code and be read from there directly on use.

Note that this is the reason those particular pointers are "const"; it is explicitly forbidden (in practice enforced by both the compiler and the libraries) to try and change those strings.

user-web.icecube.wisc.edu/~dglo/c_class/array_ptr.html shows more details.
The following user(s) said Thank You: jandulio

Please Log in or Create an account to join the conversation.

More
26 Feb 2022 21:12 #10026 by jandulio
Wow, thanks for the very good explanation on how it works and why it's okay to set those pointers like that! You can delete this thread as it's just a false alarm :)

Please Log in or Create an account to join the conversation.

Time to create page: 0.215 seconds