Skip to main content
gamedev.net
🔒 Locked

String Truncation

Started by zasz Jun 29, 2004 at 1:54 AM 5 replies 500+ views
Original Post
zasz
zasz
Hi guys, I'm just trying to debug this function that truncates a function before an occurance of a character(inclusive of the character). For example, in the string "Testing one two three", truncate the string before the first occurance of the character ' '. The result would be "one two three". Anyway, I'm only an beginner/intermediate skilled programmer and thus I have come here for your help :). The problem i'm getting is related to malloc, it crashes at runtime with a "Unhandled exception at 0x77f75a58". The code is as follows:
EXPORT LPSTR PreTruncateChr(LPSTR lpszString, CHAR cScissors, WORD wNumber)
{
   LPSTR lpszInput; 
   LPSTR lpszFinal = (LPSTR)malloc(sizeof(lpszString));
   LPSTR lpszOutput;
   WORD wCutSize = 0;

   if (lpszFinal == NULL)
      return NULL;

   if (!wNumber)
      return NULL;

   for (WORD wLoop = 0; wLoop < wNumber; wLoop++)
      lpszInput = strchr(lpszString, cScissors) + 1;

   wCutSize = (WORD)(lpszString + strlen(lpszString) - lpszInput);

   lpszOutput = (LPSTR)lpszFinal;

   for (WORD wLoop = 0; wLoop < wCutSize; wLoop++, lpszInput++, lpszOutput++)
      *lpszOutput = *lpszInput;

   *lpszOutput = '\0';

   return lpszFinal;
}
All help is greatly appreciated.
Sneftel
Sneftel
sizeof doesn't do what you think it does. It's a compile-time operator which returns the size of its operand. In this case, you're taking the sizeof an LPSTR, which on an x86 is 4 bytes. That's probably not what you want. Consider strlen instead.
Sneftel
Sneftel
The fact that you never do anything with lpszFinal after pointing it to a 4-byte block of memory, and then return it, is also a little odd.

EDIT: nevermind, you do. You forget lpszOutput's value, and then use it as a synonym for lpszFinal. I don't think that's what you want to do, either.
zasz
zasz
Ohh really? I always thought it returned the space that a variable took in memory? Thanks for your help.
Sneftel
Sneftel
Oh, and the for-loop with strchr will put the same value into lpszInput every time, since you're calling strchr with exactly the same parameters each time.
Sneftel
Sneftel
Frankly, this function's a lot more complex than it needs to be. Once you've fixed the strchr bug, you'll have a pointer pointing to the first character in what will be the result string. And the end of that string is already null-terminated. So you can just use that resultant pointer as an input to strdup, thus copying that portion of the string out to somewhere else. The whole function only needs to be about four lines long.
zasz
zasz
Yea good point, haha. I think I might just re-write it.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.