Vik*_*iev 2 c segmentation-fault dynamic-arrays
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int isPresent(char *array[], char *string, int dimension) {
for (int i=0; i<dimension; i++) {
if (strcmp(array[i], string) != 0) {
continue;
} else {
return 1;
}
}
return 0;
}
int main(int argc, char *argv[]) {
int dim = 0;
char **without_duplicates = malloc(dim * sizeof(char *));
for (int i=1; i<argc; i++) {
if (!isPresent(without_duplicates, argv[i], dim)) {
realloc(without_duplicates, (dim + 1) * sizeof(char *));
without_duplicates[dim] = malloc((strlen(argv[i]) + 1) * sizeof(char));
strcpy(without_duplicates[dim], argv[i]);
printf("%s\n", without_duplicates[dim]);
dim++;
} else {
continue;
}
}
printf("%s\n", "Not duplicated arguments:");
for (int i=0; i<dim; i++) {
printf("%s\n", without_duplicates[i]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我执行代码:./a.out rome turin rome milan venice milan florence.但是获得分段错误错误.
我试图调试代码,它一直工作到一定程度.例如,它复制rome,turin丢弃rome,复制milan,但不复制venice和其他城市.
如果它适用于某些城市,为什么不与其他城市合作?该程序具有意外的行为,并在不同的点使用不同的参数崩溃.
我不知道参数的数量和它们的长度,因此必须动态分配没有重复项的新数组.
在您的代码中,您没有将realloc的返回值分配给任何变量
realloc(without_duplicates, (dim + 1) * sizeof(char *));
Run Code Online (Sandbox Code Playgroud)
根据cppreference:
成功时,返回指向新分配内存开头的指针.必须使用
free()或取消分配返回的指针realloc().原始指针ptr无效,对它的任何访问都是未定义的行为(即使重新分配就位).失败时,返回空指针.原始指针ptr仍然有效,可能需要使用
free()或取消分配realloc().
尝试做类似的事情
char** temp = realloc(without_duplicates, (dim + 1) * sizeof(char *));
if(temp != NULL) {
without_duplicates = temp
}
else {
//handle the unsuccessful allocation
}
Run Code Online (Sandbox Code Playgroud)
注意:同样,您需要检查malloc()内存分配是否成功.