C char数组的长度与预期的不同

时间:2015-03-27 09:36:22

标签: c arrays

我有一个非常简单的代码:

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包含"________� @",因此有一些我看不到的明显内存泄漏。任何的想法?

5 个答案:

答案 0 :(得分:3)

此字符数组由字符串文字

初始化
secret[]="abcdefgh";

有9个元素,因为它还包含字符串文字的终止零。所以上面的定义相当于

secret[9]="abcdefgh";

函数strlen返回终止零之前的字符数组的元素数。所以在这个宣言中

int len=strlen(secret);

变量len8初始化 作为结果声明

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)

一次加法和一次修改

  1. char word [len];需要使用char word [len + 1];
  2. 进行更改
  3. 添加一个行世界[len] =&#39; \ 0&#39 ;;在最后一个printf行之前。
  4. 那就是它

答案 4 :(得分:0)

'\0'没有空间。

// "abcdefgh"
//  01234567

您需要为NUL终结符定义带空格的单词。

char word[len + 1];
// "abcdefgh"
//  012345678 -- word[8] gets '\0'