Ale*_*lex 0 c++ pointers runtime-error tokenize
我为最近的一个学校项目编写了一个使用指针的简单字符串标记化程序。但是,我的StringTokenizer::Next()方法遇到了问题,该方法在调用时应该返回指向 char 数组中下一个单词的第一个字母的指针。我没有收到编译时错误,但我收到了一个运行时错误,其中指出:
Unhandled exception at 0x012c240f in Project 5.exe: 0xC0000005: Access violation reading location 0x002b0000.
Run Code Online (Sandbox Code Playgroud)
该程序当前标记字符数组,但随后停止并弹出此错误。我有一种感觉,这与NULL我在我的Next()方法中所做的检查有关。
那么我该如何解决这个问题?
另外,如果您发现我可以更有效地或通过更好的练习做的任何事情,请告诉我。
谢谢!!
StringTokenizer.h:
#pragma once
class StringTokenizer
{
public:
StringTokenizer(void);
StringTokenizer(char* const, char);
char* Next(void);
~StringTokenizer(void);
private:
char* pStart;
char* pNextWord;
char delim;
};
Run Code Online (Sandbox Code Playgroud)
StringTokenizer.cpp:
#include "stringtokenizer.h"
#include <iostream>
using namespace std;
StringTokenizer::StringTokenizer(void)
{
pStart = NULL;
pNextWord = NULL;
delim = 'n';
}
StringTokenizer::StringTokenizer(char* const pArray, char d)
{
pStart = pArray;
delim = d;
}
char* StringTokenizer::Next(void)
{
pNextWord = pStart;
if (pStart == NULL) { return NULL; }
while (*pStart != delim) // access violation error here
{
pStart++;
}
if (pStart == NULL) { return NULL; }
*pStart = '\0'; // sometimes the access violation error occurs here
pStart++;
return pNextWord;
}
StringTokenizer::~StringTokenizer(void)
{
delete pStart;
delete pNextWord;
}
Run Code Online (Sandbox Code Playgroud)
主.cpp:
// The PrintHeader function prints out my
// student info in header form
// Parameters - none
// Pre-conditions - none
// Post-conditions - none
// Returns - void
void PrintHeader();
int main ( )
{
const int CHAR_ARRAY_CAPACITY = 128;
const int CHAR_ARRAY_CAPCITY_MINUS_ONE = 127;
// create a place to hold the user's input
// and a char pointer to use with the next( ) function
char words[CHAR_ARRAY_CAPACITY];
char* nextWord;
PrintHeader();
cout << "\nString Tokenizer Project";
cout << "\nyour name\n\n";
cout << "Enter in a short string of words:";
cin.getline ( words, CHAR_ARRAY_CAPCITY_MINUS_ONE );
// create a tokenizer object, pass in the char array
// and a space character for the delimiter
StringTokenizer tk( words, ' ' );
// this loop will display the tokens
while ( ( nextWord = tk.Next ( ) ) != NULL )
{
cout << nextWord << endl;
}
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
好的,只要分隔符是一个空格,我现在程序就可以正常工作了。但是如果我将它传递给一个 `/' 作为分隔符,它会再次出现访问冲突错误。有任何想法吗?
与空格一起使用的函数:
char* StringTokenizer::Next(void)
{
pNextWord = pStart;
if (*pStart == '\0') { return NULL; }
while (*pStart != delim)
{
pStart++;
}
if (*pStart = '\0') { return NULL; }
*pStart = '\0';
pStart++;
return pNextWord;
}
Run Code Online (Sandbox Code Playgroud)
访问冲突(或某些操作系统上的“分段错误”)意味着您试图读取或写入您从未分配的内存位置。
考虑 Next() 中的 while 循环:
while (*pStart != delim) // access violation error here
{
pStart++;
}
Run Code Online (Sandbox Code Playgroud)
假设字符串是"blah\0". 请注意,我已经包含了终止空值。现在,问问自己:当循环到达字符串的末尾时,它是如何知道停止的?
更重要的是:*pStart如果循环未能在字符串末尾停止会发生什么?