c - 我的 strlen 在 2 个不同的编译器中工作不同,任何解释?

标签 c malloc strlen

<分区>

我正在使用我安装的 gcc 编译器,它是从我的 cmd 运行的(在编辑器可视代码中编写)&为了调试我还安装了 visual studio。 这是我的第二个学期,我刚刚学习了 malloc/calloc 等。

所以行:

ch_pointer = (char *)malloc(length * sizeof(char));

在我的 gcc 编译器中,当我使用 strlen(ch_pointer)24 作为答案时返回。

如果我使用的数字太大(例如 100)作为长度,它也会显示 strlen(ch_pointer) == 0

如果我在 visual studio 中将其编写为:

ch_pointer = (char *)malloc(((length + 1) * sizeof(char)) / 2 - 1);

这是唯一完美运行的情况。

get_number() 函数很好,它只是确保您将键入一个 int 类型。

void main() {
    char *ch_pointer = '\0';
    int length = 0;
    printf("Please write down your sentence length in characters (including spaces): ");
    length = get_number();

    ch_pointer = (char *)malloc(((length + 1) * sizeof(char)) / 2 - 1); 
    ch_pointer[strlen(ch_pointer) - 1] = '\0';

    printf("Please write down your sentence: ");
    for (int filling = 0; filling < strlen(ch_pointer); filling++)
        scanf(" %c", &ch_pointer[filling]);
    for (int printing = 0; printing < strlen(ch_pointer); printing++)
        printf("%c", ch_pointer[printing]);

    free(ch_pointer);
}

如果我写下 4 甚至 100 以获得数组长度 5101,两个编译器的工作方式相同'\0' 结尾 & 让我完美地输入和打印:

length = 4
strlen(ch_pointer) == 4

length = 100
strlen(ch_pointer) == 100

最佳答案

这里有一个基本的误解:strlen 不知道您传入的数组的分配大小;它只是遍历它直到找到一个空字符,然后返回它必须跳过的字符数。

因为 malloc 返回一个指向未初始化内存的指针,它的内容是不可预测的,所以调用 strlen 是未定义的行为 - 在内存块没有的最坏情况下零,它甚至会在它外面继续阅读,希望使程序崩溃。

关于c - 我的 strlen 在 2 个不同的编译器中工作不同,任何解释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55721440/

相关文章:

c - 如何使函数返回指向 C 中新字符串的指针?

c - 你怎么知道用 malloc() 分配多少空间?

c++ - 如何知道应用程序中可用的虚拟内存

c - 不使用 sizeof(type),使用 sizeof *p,是否安全正确?

c - snprintf + 鹅卵石

c - C中二维数组的最大尺寸

C Linux 检查挂载空间

c - 访问C中的外部分配空间

c - 在c中用strlen验证

c - 为什么 strlen 在没有 '\0' 的情况下工作正常?