【发布时间】: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