动态字符数组 C 中的随机字符

random chars in dynamic char array C

我需要有关 char 数组的帮助。我想创建一个 n-lenght 数组并初始化它的值,但是在 malloc() 函数之后数组比 n*sizeof(char) 长,并且数组的内容不仅仅是我分配的字符......在数组中很少随机字符,我不知道如何解决...我需要一个项目的那部分代码用于学校考试,我必须在星期天之前完成...请帮忙:P

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

int main(){

    char *text;

    int n = 10;

    int i;

    if((text = (char*) malloc((n)*sizeof(char))) == NULL){
        fprintf(stderr, "allocation error");
    }

    for(i = 0; i < n; i++){
        //text[i] = 'A';
        strcat(text,"A");
    }

    int test = strlen(text);
    printf("\n%d\n", test);

    puts(text);
    free(text);

    return 0;
}

那么在使用 strcat 之前制作

text[0]=0;

strcat 期望第一个参数也为空终止 char 数组。

来自standard 7.24.3.1

  #include <string.h>
          char *strcat(char * restrict s1,
               const char * restrict s2);

The strcat function appends a copy of the string pointed to by s2 (including the terminating null character) to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1.

如果你不知道,你认为 strcat 怎么知道第一个字符串的结尾 在 s1.

中放一个 [=16=]

另外不要忘记为 [=16=] 字符分配一个额外的字节。否则你写的是你分配的内容。这又是未定义的行为。

之前你有未定义的行为。

注:

  • 您应该检查 malloc 的 return 值以了解 malloc 调用是否成功。

  • 不需要转换 malloc 的 return 值。在这种情况下,从 void* 到相关指针的转换是隐式完成的。

  • strlen returns size_t 不是 intprintf("%zu",strlen(text))

首先,您是在

中使用 malloc 的方式
text = (char*) malloc((n)*sizeof(char)

不理想。您可以将其更改为

text = malloc(n * sizeof *text); // Don't cast and using *text is straighforward and easy. 

所以语句可以是

if(NULL == (text = (char*) malloc((n)*sizeof(char))){
    fprintf(stderr, "allocation error");
}

但实际问题出在

for(i = 0; i < n; i++){
    //text[i] = 'A';
    strcat(text,"A");
}

strcat 文档说

dest − This is pointer to the destination array, which should contain a C string, and should be large enough to contain the concatenated resulting string.

只是指出上面的方法是有缺陷的,你只需要考虑C字符串"A"中实际上包含两个字符,A和终止 \0(空字符)。在这种情况下,当 in-2 时,您有越界访问或缓冲区溢出 1。如果你想用 A 填充整个 text 数组,你可以完成

for(i = 0; i < n; i++){ 
    // Note for n length, you can store n-1 chars plus terminating null
    text[i]=(n-2)==i?'A':'[=14=]'; // n-2 because, the count starts from zero
}
//Then print the null terminated string
printf("Filled string : %s\n",text); // You're all good :-)

注意:使用像 valgrind 这样的工具来查找内存泄漏和越界内存访问。