c++ - strstr 在 codeforces 上的 C++ 4.7 中不起作用

标签 c++ function strstr strncpy

在在线编译器上,该程序在输入 "ABACABA" 时给出了完美的输出,但在 Codeforces 测试中它只是发布了最后一行。在调试时,我发现当使用 strstr() 时,指针 u 指示指向地址 0。我无法理解为什么该功能在其他在线编译器上有效,但在 Codeforces 上无效。

编辑:好的,感谢@Jeremy Friesner,我发现实际上是 strncpy 无法正常工作,因为现在自定义测试用例编译器为“str”提供了错误的输出。仍然不知道为什么它在两个不同的编译器上会有不同的行为,我应该做些什么改变。

#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<stdlib.h>
using namespace std;


int main()
{
    char *s;
    int length=20;
    s = (char *) malloc(length*(sizeof(char)));
    char c;
    int count=0;
    while((c=getchar())>='A')
    {
        if(c<='Z')
        {
           //cout<<count;
           if(length>=count)
           {
               s = (char *) realloc(s,(length+=10)*sizeof(char));
           }
           s[count++]=c;    
           //printf("%p\n",s);

        }
        else
        {
            break;
        }
   }
   char *u=s;
   int o=1;
   //printf("%p\n",s);
   while(u)
   {
       char *str = (char *) malloc(o*sizeof(char));
       str = strncpy(str,s,o);
       //cout<<str<<endl;
       char *t;
       u = strstr(s+1,str);
       //printf("u %p\n",u);
       t=u;
       int ct=0;
       char *p;
       while(t)
       {  
           ct++;
           p=t;
           t = strstr(t+o,str); 
       }

       ct=ct+1;
       //cout<<"here"<<endl;
       if(p==(s+count-o))
       {
           cout<<o<<" "<<ct<<endl;
       }
       //cout<<ct<<endl;
       o++;

   }
   cout<<count<<" "<<1;
}

最佳答案

如评论中所述,一个主要问题是您在读入字符串后没有以 null 结尾,这会导致奇怪的结果。具体来说,它会导致您调用未定义的行为,这总是一件坏事。 malloc()分配的内存和realloc()分配的额外内存不保证归零。

您可以通过添加以下内容来解决问题:

s[count] = '\0';

就在之前:

char *u = s;

严格来说,您还应该检查 malloc()realloc() 的返回值。另外,你不应该使用成语:

x = realloc(x, newsize);

如果 realloc() 失败,您将丢失指向原始数据的指针,因此您已经泄漏了内存。安全的工作方式是:

void *space = realloc(x, newsize);
if (space == 0)
    …report error etc…
x = space;
x_size = newsize;

可能还有其他问题;我没有仔细检查每个可能出现的问题的代码。

关于c++ - strstr 在 codeforces 上的 C++ 4.7 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23818770/

相关文章:

C++ 防止方法重写

C++ `if` 似乎走错了分支?

c++ - 模板参数绑定(bind)

c++ - std::vector 内部结构

function - unityscript 中的基本功能

c - 在 txt 中使用 strstr() 找到一个字符串

python - 没有括号定义函数?

python - 从函数返回用户提供的值

c - 使用自制的 strstr() 函数检查其他字符串中嵌入的字符串,然后将其替换为其他字符串(由用户输入)

c - 如何在c中的两个字符串之间查找文本