我有一个非常简单的代码:
secret[]="abcdefgh";//this is declared in different function and is random word
int len=strlen(secret);//ofc it is 8 in this case
char word[len];
for(int a=0;a<len;a++){//expecting this will put '_' at positions 0-7
word[a]='_';
}
printf("%d %s",(int)strlen(word),word);
但是,strlen(word)
返回11而word
包含"________� @"
,因此有一些我看不到的明显内存泄漏。任何的想法?
答案 0 :(得分:3)
此字符数组由字符串文字
初始化secret[]="abcdefgh";
有9个元素,因为它还包含字符串文字的终止零。所以上面的定义相当于
secret[9]="abcdefgh";
函数strlen
返回终止零之前的字符数组的元素数。所以在这个宣言中
int len=strlen(secret);
变量len
由8
初始化
作为结果声明
char word[len];
相当于
char word[8];
在这个循环中
for(int a=0;a<len;a++){//expecting this will put '_' at positions 0-7
word[a]='_';
}
aray的所有元素都设置为'_'
。 arry没有终止零。因此,向数组中添加函数strlen
具有未定义的行为。
您可以通过以下方式更改循环
int a = 0;
for(;a<len - 1;a++){//expecting this will put '_' at positions 0-7
word[a]='_';
}
word[a] = '\0';
在这种情况下,函数strlen
将返回数字7
,程序将格式正确。
答案 1 :(得分:2)
乍一看,似乎你忘了在char数组(指针)的末尾加上null。
根据我的经验,这会导致缓冲区溢出或堆栈损坏。
答案 2 :(得分:2)
你只需要将null终止字符串,将len
增加1并使null终止你的字符串。
#include <stdio.h>
#include <string.h>
int main(void)
{
char secret[]="abcdefgh";
int len=strlen(secret);
char word[len+1];
for(int a=0;a<len;a++)
{
word[a]='_';
}
word[a]=0; //or word[a]='\0'
printf("%d %s",(int)strlen(word),word);
return 0;
}
关于内存泄漏是的,它可以。
答案 3 :(得分:1)
一次加法和一次修改
那就是它
答案 4 :(得分:0)
'\0'
没有空间。
// "abcdefgh"
// 01234567
您需要为NUL终结符定义带空格的单词。
char word[len + 1];
// "abcdefgh"
// 012345678 -- word[8] gets '\0'