首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >strcmp分段故障

strcmp分段故障
EN

Stack Overflow用户
提问于 2011-01-06 01:07:09
回答 8查看 3K关注 0票数 2

这是来自spoj的一个问题。与算法无关,只是c++。

样本输入

2

A aa bb cc def ghi

A bb c c c

样本输出

3.

5

它计算相同单词的最长序列http://www.spoj.pl/problems/WORDCNT/这个单词少于20个字符,但当我运行它时,它给出了分割错误。我使用eclipse对其进行了调试。这就是它崩溃的地方

代码语言:javascript
复制
if (strcmp(previous, current) == 0)
                currentLength++;

使用以下消息

"strcmp() at 0x2d0100“没有源代码,有什么问题吗?

代码语言:javascript
复制
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
using namespace std;
int main(int argc, const char *argv[])
{
    int t;
    cin >> t;
    while (t--) {
        char line[20000], previous[21], current[21], *p;
        int currentLength = 1, maxLength = 1;
        if (cin.peek() == '\n') cin.get();
        cin.getline(line, 20000);

        p = strtok(line, " '\t''\r'");
            strcpy(previous, p);

        while (p != NULL) {
            p = strtok(NULL, " '\t''\r'");
            strcpy(current, p);

            if (strcmp(previous, current) == 0)
                currentLength++;
            else
                currentLength = 1;
            if (currentLength > maxLength)
                maxLength = currentLength;
        }
        cout << maxLength << endl;
    }
    return 0;
}
EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2011-01-06 01:37:46

问题可能出在这里:

代码语言:javascript
复制
    while (p != NULL) {
        p = strtok(NULL, " '\t''\r'");
        strcpy(current, p);

而当进入循环时,p可以不为空。

当对其使用strcpy时,它可能为NULL。

更正确的循环形式应该是:

代码语言:javascript
复制
    while ((p != NULL) && ((p = strtok(NULL, " \t\r")) != NULL))
    {
        strcpy(current, p);

请注意。在C++中标记一个流要容易得多。

代码语言:javascript
复制
std::string  token;
std::cin >> token;  // Reads 1 white space seoporated word

如果您想对行进行标记

代码语言:javascript
复制
// Step 1: read a single line in a safe way.
std::string line;
std::getline(std::cin, line);

// Turn that line into a stream.
std::stringstream  linestream(line);

// Get 1 word at a time from the stream.
std::string token;
while(linestream >> token)
{
    // Do STUFF
}
票数 9
EN

Stack Overflow用户

发布于 2011-01-06 01:19:39

忘记在strtok上检查NULL,完成后将返回NULL,并且您不能在strcpy、strcmp等上使用该NULL。

请注意,您在strtok之后立即执行了strcpy,您应该在使用p作为源之前检查是否为null。

票数 2
EN

Stack Overflow用户

发布于 2011-01-06 01:40:53

strtok手册页上写着:

代码语言:javascript
复制
 Each call to strtok() returns a pointer to a null-terminated string containing the next 
token. This string does not include the delimiting character. If no more tokens are found, 
strtok() returns NULL. 

在你的代码中,

代码语言:javascript
复制
while (p != NULL) {
            p = strtok(NULL, " '\t''\r'");
            strcpy(current, p);

一旦解析完整个字符串,您就不会检查NULL (对于p)。在此之后,您将尝试在current中复制p(现在为空),从而导致崩溃。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4606907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档