-3

程序应该从文件中获取字符串并将它们分开,在其中找到字符串“delim”。我应该使用动态内存,但很抱歉我不能完美地使用它。在循环的第一次迭代之后将“cpystr”从“SUCCESSZOMBIEAAAAAAAaaaaAZOMBIEaaAZOMBIEdf”更改为 NULL 的原因是什么?“SUCCESSZOMBIEAAAAAAAaaaAZOMBIEaaAZOMBIEdf”,其中“ZOMBIE”是“delim”。帮我解决这个问题。感谢您提前提供帮助!

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string>

char** split(const char *str, const char *delim)
{
    int cntr1, cntr2, cntr3, cntdelim=0;
    bool check;
    //counting "delim" in the str

    char **maspntr=NULL;
    char *cpystr=NULL;
    cpystr=_strdup(str); //reserve copy of the "cpy"
    strcpy(cpystr,str);
    for (cntr1=0;cntr1<(strlen(cpystr)+1);cntr1++) //THE PROBLEM WITH THIS CYCLE!
    {

    check=1;
    for (cntr2=0, cntr3=cntr1;cntr2<strlen(delim); cntr2++, cntr3++) //searching for "delim" 
        if (!(cpystr[cntr3]==delim[cntr2]))
            {

                check=0;
                break;
            }
        if (check) //if it's foound, it copies the first N characters as the first element of pointers' array 
        {

            maspntr=(char**)realloc(maspntr,(cntdelim+1)*sizeof(char*));
            maspntr[cntdelim]=(char*)calloc(cntr1, sizeof(char));
            cntdelim++;
            for (cntr3=0;cntr3<=(strlen(cpystr)-(cntr1+strlen(delim)-2));cntr3++)
            {
                cpystr[cntr3]=cpystr[cntr3+cntr1+strlen(delim)];
                cpystr=(char*)realloc(cpystr,(strlen(cpystr)+1-cntr1-strlen(delim))*sizeof(char)); //delete first N characters +"delim" by copying the characters from the end then modifying memory
            }

        }
         if(cpystr[cntr1]='\0') //if it is the end of string return
         {

             for (cntr1=0; cntr1<sizeof(maspntr); cntr1++)
         {
             printf(maspntr[cntr1],'\n');
         }
             free(cpystr);

             return(maspntr);
         }

    }   //Changing "cpystr" to NULL right here






}
int main()
{
    char singlech;
    int len=0;

    //copy string from the file to the variable
    FILE* foo;
errno_t err;
    err=fopen_s(&foo,"input.txt","r");
    if( err == 0 )
  {
      printf( "The file 'input.txt' was opened\n" );
  }
  else
  {
      printf( "The file 'input.txt' was not opened\n" );
  }
    while (!feof(foo))  //rather stupid way of getting memory
    {
        fscanf_s(foo, "%c", &singlech);
        len++;
    }
    char *str=NULL, *delim=NULL;

    str=(char*)calloc(len,sizeof(char));
    rewind(foo);
    fgets(str,len,foo);
    delim=(char*)calloc(sizeof("ZOMBIE")+1, sizeof(char));
    strcpy(delim,"ZOMBIE");
    split(str,delim);
    printf(str);
    free(str);
    free(delim);

    getchar();

}
4

1 回答 1

2

我没有阅读您的所有代码,但是

cpystr = (char*)malloc(sizeof(cpystr))

分配“指针大小”字节(可能是 4 或 8),因此以下strcpy() 写入超出分配的内存。

你大概是说

cpystr = malloc(strlen(str) + 1); // casting the return value of malloc not needed

但是为什么不简单地写

cpystr = strdup(str);

而不是malloc() + strcpy()

于 2013-10-13T18:15:20.127 回答