【发布时间】:2017-09-08 20:15:05
【问题描述】:
编辑:仅包含相关代码
我必须操作一个看起来像这样的输入字符串
create /foo
create /foo/bar
write /foo/bar "text"
create /foo/bar/baz
我已经创建了这个程序(你不需要看全部)
我遇到的问题是在main() 中调用的函数printAllFolders(),它在main() 函数下定义。问题一定出在那个函数上。在结构path[]中传递字符串是否正确
comando->path?
当我将该函数放在 main 中时,它确实给我带来了分段错误问题。其余的工作正常。
编辑:为了清楚起见,printAllFolders() 确实打印了路径数组中的所有字符串,所以我只需要传递path[255] 数组,而不是具有所有两个索引的那个。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct _command {
unsigned char command[10];
unsigned char path[255][255];
int pathLevels;
} command;
command* createCommandMul(unsigned char* str);
void printfAllFolders(unsigned char* stringhe, int lengthArray);
int main() {
command* comando = (command*) malloc(sizeof(command));
unsigned char* upPath = NULL;
unsigned char* allPath = NULL;
FILE* fp;
unsigned char* line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/Users/mattiarighetti/Downloads/semplice.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
comando = createCommandMul(line);
upPath = upperPath(comando);
allPath = fullPath(comando);
printfAllFolders(comando->path, comando->pathLevels);
}
fclose(fp);
if (line)
free(line);
return 0;
}
void printfAllFolders(unsigned char* stringhe, int lengthArray) {
unsigned char* stringa = stringhe;
int length = lengthArray;
if (length == 0) printf("Cartella %s", stringa[length]);
for (int i = 0; i < length+1; i++) {
printf("Cartella %d %s\t", i, stringa[i]);
}
}
command* createCommandMul(unsigned char* str) {
unsigned char* c = str;
command* commandPointer = (command*) malloc(sizeof(command));
int commandIndex = 0;
int pathLevel = 0;
int pathIndex = 0;
/* Parte Comando */
while(*c != ' ' && commandIndex<10) {
commandPointer->command[commandIndex] = *c++;
commandIndex++;
}
commandPointer->command[commandIndex] = '\0';
while(*c == ' ') c++;
while(*c == '/') c++;
/* Parte Path*/
while(*c!='\0') {
if (*c == '/') {
commandPointer->path[pathLevel][pathIndex] = '\0';
pathLevel++;
pathIndex = 0;
c++;
} else {
commandPointer->path[pathLevel][pathIndex] = *c++;
pathIndex++;
}
}
commandPointer->path[pathLevel][pathIndex] = '\0';
commandPointer->pathLevels = pathLevel;
return commandPointer;
}
【问题讨论】:
-
lengthArray参数是否告诉您数组中有多少个字符串或最后一个有效元素是什么?如果是前者,那么您正在阅读数组的末尾。如果是后者,则参数名称具有误导性。 -
另外,这不是您的段错误的原因,但看起来您正在泄漏您分配的所有
command对象。 -
我在代码中弄得有点乱,所以如果它读取像
create /foo/dir这样的命令,lengthArray参数确实告诉你数组中有 2 个字符串,它们是foo和dir@MichaelBurr -
泄露是什么意思? @MichaelBurr
-
您是否尝试过调试代码以查看错误发生在什么地方和什么情况下以隔离和最小化再现情况?至少有两行代码可以访问数组边界之外的内存。
标签: c string function pointers