Codeforces 4C运行时错误

Codeforces 4C Runtime Error

本文关键字:运行时错误 4C Codeforces      更新时间:2023-10-16

嗨,我正在使用Trie实现来解决这个问题,但是在codeforces的服务器中,我得到了运行时错误,在我的pc和Ideone上是正常的。有什么想法吗?http://codeforces.com/contest/4/problem/Chttps://ideone.com/dvRL3b

#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>

using namespace std;
#define MAXN  ('z'-'a'+2)
#define VALUE(c) ( (c)-'a' )
struct Trie
{
    Trie *m[MAXN];
    int count;
}trie;
int insert(Trie *  t, char * w){
    if(w[0]==''){
        t->count++;
        return t->count;
    }
    if(t->m[VALUE(w[0])] == NULL){
        t->m[VALUE(w[0])] =(Trie *) malloc(sizeof(Trie));
    }
    return insert(t->m[VALUE(w[0])] , w+1);
}   

int main(){
    int t;
    scanf("%d",&t);
    for (int i = 0; i < t; ++i)
    {
        char *w = NULL;
        w = (char *)malloc(sizeof(char));
        scanf("%s",w);
        //printf("%sn", w);
        int resp = insert(&trie,w); 
        if(resp > 1){
            printf("%s%dn", w,resp-1);
        }else{
            printf("OKn");
        }
    }

    return 0;
}

这一行:

w = (char *)malloc(sizeof(char));

将只分配一个字节的内存。

这个问题中的请求最多32个字符,所以尝试:

w = (char *)malloc(sizeof(char)*33); // include 1 extra byte for zero termination byte

此外,在为每个新Trie分配内存时,您可能应该使用calloc,即更改

t->m[VALUE(w[0])] =(Trie *) malloc(sizeof(Trie));

t->m[VALUE(w[0])] =(Trie *) calloc(sizeof(Trie),1);