【问题标题】:Am I returning double char the correct way?我是否以正确的方式返回双字符?
【发布时间】:2021-03-18 17:22:46
【问题描述】:

我目前正在练习 malloc 并尝试在 c 中创建一个字符串数组。 以下是我的小程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read_arguments(char*s[]);
char** copy_argv(char*s[]);
void free_char_ary(char*s[]);
int main(int argc, char* argv[])
{
    int count = read_arguments(argv);
    
    char **arr = copy_argv(argv);
    for(int i = 0; i < count; i++)
    {
        printf("%s\n", arr[i]);
    }

    free_char_ary(arr);
    exit(0);
}

int read_arguments(char*s[])
{
    int count = 0;
    
    while(*s) 
    {
        count++;
        s++;
    }
    
    return count;
}


char** copy_argv(char*s[])
{
    int result = read_arguments(s);
    printf("result = %d\n", result);
    char** ary = (char**) malloc(result * sizeof(char*));
    for(int i = 0; i < result; i++)
    {
        ary[i] = (char*) malloc(100 * sizeof(char));
        strcpy(ary[i], s[i]);        
    } 
    return ary;
}

void free_char_ary(char*s[])
{
    int count = read_arguments(s);
    printf("count = %d\n", count);
    for(int i = 0; i < count; i++)
    {
        free(s[i]);
    }
    free(s);
}

结果很奇怪。如果我执行类似 4 个参数,那很好,但如果我执行 5 个参数,那么我会在 free_char_ary 处出现分段错误。我发现在我将_argv复制到char**arr之后,read_arguments返回的int是不同的。我是否以正确的方式使用双字符指针?为什么结果不一样?

【问题讨论】:

    标签: c command-line-arguments dynamic-memory-allocation undefined-behavior null-pointer


    【解决方案1】:

    函数free_char_ary 具有未定义的行为,因为动态分配的数组不包含值为NULL 的元素。因此,在函数内调用read_arguments 会调用未定义的行为。

    void free_char_ary(char*s[])
    {
        int count = read_arguments(s);
        printf("count = %d\n", count);
        for(int i = 0; i < count; i++)
        {
            free(s[i]);
        }
        free(s);
    }
    

    您应该以与定义数组argv 相同的方式为动态分配的数组附加一个空指针。或者您可以将动态分配的数组中的实际元素数量传递给函数,

    【讨论】:

    • 您好弗拉德,谢谢您的回复。你是对的,在我在 copy_argv 中执行 ary[result] = NULL 之后,一切都运行良好。谢谢!
    猜你喜欢
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多