首页 > 解决方案 > 指针的内存分配适用于固定变量分配的字符串,但不适用于用户输入字符串

问题描述

例如,给定程序适用于代码中固定的字符串

char str[100] = "With fixed string this code works"
// Output of the program is "fixed string this code works"

但是一旦我使用str输入

scanf("%s", &str);

似乎在内存分配中发现了错误,因为在给出输入后代码返回错误值。

完整代码如下

int main (void) {
    char str[100];
    char *p = (char *)malloc(sizeof(char) * str[100]);
    printf("Enter something: ");
    scanf("%s", &str);
    *p = str;
    p = strchr(str, ' ');
    puts(p + 1);

    // Check for the first space in given input string if found then 
    while (*p++)
        if (*p == ' ' && *++p)
            printf("%s", *p);

    printf ("\n\n");

    return 0;
}

不确定在使用scanf函数输入字符串时是否需要动态内存分配任何其他分配过程

标签: cscanfdynamic-memory-allocationfgetsc-strings

解决方案


malloc有一个错误:

char *p = (char *)malloc(sizeof(char)*str[100]);

让我们先简化一下。


不要强制转换malloc(请参阅:我是否强制转换 malloc 的结果?):

char *p = malloc(sizeof(char)*str[100]);

sizeof(char)(根据定义)在所有架构上始终为1 ,无论它占用多少位,所以我们可以消除它:

char *p = malloc(str[100]);

现在我们有:

char str[100];
char *p = malloc(str[100]);

你有未定义的行为str没有值(即未初始化),并且您传递的元素是数组末尾之后的元素,因此您有未定义的行为。

因此,传递给的长度参数malloc是随机的。


推荐阅读