gpt4 book ai didi

第一次循环迭代后将字符串更改为 NULL。内存分配

转载 作者:行者123 更新时间:2023-11-30 20:15:28 25 4
gpt4 key购买 nike

程序应该从文件中获取字符串并将它们分开,在其中找到字符串“delim”。我应该使用动态内存,但抱歉我不能完美地使用它。在循环的第一次迭代后将“cpystr”从“SUCCESSZOMBIEAAAAAAAaaaAZOMBIEaaAZOMBIEdf”更改为 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();

}

最佳答案

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

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()

关于第一次循环迭代后将字符串更改为 NULL。内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19348453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com