Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.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
不可见内存泄漏?-malloc和strcpy_C_Memory - Fatal编程技术网

不可见内存泄漏?-malloc和strcpy

不可见内存泄漏?-malloc和strcpy,c,memory,C,Memory,我编译了我的代码,前两次它崩溃了。我没有改变任何东西,再次编译,第三次和第四次编译过程运行良好,没有任何崩溃 前两次崩溃并没有立即发生,它已经打印了我的printf声明,并立即强制关闭 这是我的密码: #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char testString[] = "Yiu Rules"; char* destString = (c

我编译了我的代码,前两次它崩溃了。我没有改变任何东西,再次编译,第三次和第四次编译过程运行良好,没有任何崩溃

前两次崩溃并没有立即发生,它已经打印了我的printf声明,并立即强制关闭

这是我的密码:

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

int main()
{
  char testString[] = "Yiu Rules";
  char* destString = (char*)malloc(sizeof(strlen(testString))*2);

  strcpy(destString, testString);

  printf("%s", destString);

  free(destString);

  return 0;

}
#包括
#包括
#包括
int main()
{
char testString[]=“Yiu规则”;
char*destString=(char*)malloc(sizeof(strlen(testString))*2);
strcpy(destString,testString);
printf(“%s”,字符串);
自由(字符串);
返回0;
}
有什么想法吗?

sizeof(strlen(testString))
不是你想象的那样。您可以计算由
strlen
返回的值的大小(以字节为单位),即
size\u t

只需使用strlen(testString)

这就是为什么
strcpy
不是一个安全的函数,您应该使用
strncpy
分配
sizeof(strlen(testString))*2个字节的内存。这似乎没有道理
sizeof(strlen(testString))*2
sizeof(size\u t)*2
,通常不足以容纳字符串

sizeof(size_t)*2通常在64位或32位平台上分别为16或8字节的内存。在64位平台上,您的代码将“存活”,因为您的字符串可以容纳16个字节。但在32位平台上,它将不适合,它将溢出分配的内存并损坏堆

这个

如果你想尝试过多分配内存的话,可能会有一些道理,但我不清楚
sizeof
的来源和原因。

sizeof(strlen(testString))确实是不正确的,但它显示了一个很好的实践,即对char类型使用sizeof操作符。在您使用sizeof的情况下,它的大小不是您想要的大小,strlen已经提供了要传递给malloc的字节数,但是如果您也想使用sizeof,下面是一种正确的方法:

(char *)malloc(sizeof(char) * strlen(testString) * 2 + 1).
注意malloc结尾的+1:strlen不计算它正在计算长度的字符串的终止空字节。然后strcpy可能会工作,但最终也可能会出现总线错误或某种错误,因为您试图将\0(在strcpy中)附加到内存的未保留部分


此外,您的malloc可能会返回一个已经使用过的内存区域(但在像您提供的那样的短程序中很少发生),因此您可以在分配后立即使用bzero,以确保您使用的是干净的内存。

您也不应该对以零结尾的字符串使用
strncpy
。如果您想要一个“安全”的字符串复制函数,它将是
strlcpy
(不幸的是,这是非标准的)。但总的来说,当字符串不适合内存时截断字符串的整个想法是相当值得怀疑的。啊,谢谢你的快速回答,谢谢:)我想目前我对strcpy还不错,最好在学习高级东西之前先掌握基本知识。哦,我对编程还很陌生,我认为您总是需要sizeof操作符,因为从语义角度来看,它对我来说是有意义的。但是谢谢你的澄清@Yíu:您可以在其中使用
sizeof
,例如
char*destString=malloc((strlen(testString)+1)*sizeof*destString)。但是
sizeof(char)
始终为1,这意味着您可以将其作为乘数忽略。这是个人品味的问题。每当你在C代码中遇到某种深奥的错误时,可能是内存问题。在这种情况下,他是你的朋友。
(char *)malloc(sizeof(char) * strlen(testString) * 2 + 1).