Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C中free()函数的问题_C_Pointers_Malloc_Strlen - Fatal编程技术网

C中free()函数的问题

C中free()函数的问题,c,pointers,malloc,strlen,C,Pointers,Malloc,Strlen,我在中有一个while循环,用于处理字符串。下面是我的代码的基本结构: char myString[1000]; //Initialize and maybe change myString for(/*conditions*/){ while(/*conditions*/){ if(strchr(myString,' ') == NULL){ break; } char *temp = malloc(sizeof(

我在
中有一个
while
循环,用于处理字符串。下面是我的代码的基本结构:

char myString[1000];
//Initialize and maybe change myString
for(/*conditions*/){
    while(/*conditions*/){
        if(strchr(myString,' ') == NULL){
            break;
        }
        char *temp = malloc(sizeof(char) * strlen(myString));
        strcpy(temp,myString);
        *strchr(temp,' ') = '\0';
        strcat(myString," ");
        strcat(myString,temp);
        free(temp);
    }
}
有时,这段代码工作得很好,但有时进程结束并返回3,这意味着有一个错误(3是我尝试在我不喜欢的地方使用NULL时通常得到的返回值,例如
myPointer->example
其中
myPointer
为NULL)。经过一些测试,我发现导致问题的线路是
free(temp)。我试图用
if(temp!=NULL){free(temp);}
替换它,但它没有改变任何东西。我试图用
char temp[1000]
而不是
malloc
声明
temp
,并拿走
free(temp)行,但它仍然做同样的事情。如果我拿走
免费(temp)行,仍然使用
malloc
问题解决了,但是内存出现了巨大泄漏,所以我不能这样做。是否有错误取决于
myString
字符串中的内容,这意味着如果其中存在某个值,则始终存在错误,如果存在另一个特定值,则永远不会有错误,但我无法找出哪种类型的值有效,哪种类型的值无效,这似乎是随机的


为什么
免费(临时)有时工作,有时不工作,如何让它始终工作?

主要问题是,您分配的元素比所需的内存少一个

strlen()。后来呢,

strcpy(temp,myString);
实际上是调用的越界访问(存储终止null)。因此,你可以看到

有时,此代码工作正常,但有时进程结束并返回3,这意味着存在错误[…]

要解决此问题,您应该修改分配语句,如下所示

char *temp = malloc(strlen(myString) + 1); // +1 for terminating null,
                                           // sizeof(char) == 1, guaranteed by C standard.
也就是说,从

strchr()
strrchr()
函数返回指向匹配字符的指针,如果找不到字符,则返回NULL。[…]

对于突出显示的场景

*strchr(temp,”)='\0'


尝试取消引用无效的空指针常量(
null
),然后再次调用UB。在取消引用返回指针之前,请检查有效的返回值

char*temp=malloc(sizeof(char)*strlen(myString));strcpy(temp,myString)越界写入,未定义行为。另外,如果
strchr()
返回
NULL
,则
NULL
的未定义行为将取消引用。此外,
sizeof(char)
是一个定义的行为,因此它作为传递给
malloc()
的参数的一部分是多余的。我投票结束这个问题,因为这个问题是由一个简单的打字错误引起的。。。。。如果发生UB,任何预期或意外的结果都可能发生。@haccks好的,先生,刚才引用了问题中的部分,使之相关。:)@DonaldDuck检查答案中的编辑,如果问题仍然存在,请创建一个MCVE。@SouravGhosh我在开始时已经用
if(strchr(myString,,)==NULL){break;}
处理了这个问题。因此,
strchr(test,”)
不应为NULL,因为此时test和myString是相同的,如果myString中没有任何空间,它将退出while循环。@DonaldDuck有道理,删除了该选项。