遍历数组时C中的分段错误
我试图模仿一种基本的加密算法。我尝试读取加密的数据文件,并在JRB树(在我的例子中是简单的键值对)中查找每个对应的值,该树基本上是从“.key”文件填充的,然后将其写入另一个文件遍历数组时C中的分段错误,c,tree,segmentation-fault,C,Tree,Segmentation Fault,我试图模仿一种基本的加密算法。我尝试读取加密的数据文件,并在JRB树(在我的例子中是简单的键值对)中查找每个对应的值,该树基本上是从“.key”文件填充的,然后将其写入另一个文件 #include <fcntl.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include "fields.h" #include <cJSON.h> #in
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "fields.h"
#include <cJSON.h>
#include "jrb.h"
void decrypt();
int main(int argc, char **argv)
{
decrypt();
return 0;
}
void decrypt()
{
IS is_input;
FILE *fp;
int i, j;
char *buffer = 0;
char *str = 0;
long length;
FILE *f = fopen ("data/.key", "rb");
cJSON *json;
JRB b, tmp;
b = make_jrb();
tmp = make_jrb();
is_input = new_inputstruct("data/encrypted");
if (is_input == NULL) {
perror("Error: ");
exit(1);
}
fp = fopen("data/decrypted.txt", "w+");
if (fp < 0) { perror("Error: "); exit(1); }
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
{
fread (buffer, 1, length, f);
}
fclose (f);
}
if (buffer)
{
json = cJSON_Parse(buffer);
cJSON *current_element = NULL;
char *current_key = NULL;
cJSON_ArrayForEach(current_element, json)
{
current_key = current_element->string;
if (current_key != NULL)
{
(void) jrb_insert_str(b, strdup(current_element->valuestring), new_jval_v(current_key));
}
}
while(get_line(is_input) >= 0) {
for (i = 0; i < is_input->NF; i++) {
str = is_input->fields[i];
tmp = jrb_find_str(b, "10001011"); // This works but when I use "str" here instead of "10001011", I get a segmentation fault.
// tmp = jrb_find_str(b, str);
fprintf(fp, "%s ", tmp->val.s);
}
}
}
jettison_inputstruct(is_input);
fclose(fp);
return;
}
在使用printf运行程序后,我在打印后得到一个分段错误,数据如下:
0 10 11分段故障(堆芯转储)
但是如果我尝试使用fprintf将其写入另一个文件,我会直接得到分段错误。
我试着调试,我看到tmp值是空的,但它怎么可能是空的呢
关于JRB:
输入结构:
const char *name; /* File name */
FILE *f; /* File descriptor */
int line; /* Line number */
char text1[MAXLEN]; /* The line */
char text2[MAXLEN]; /* Working -- contains fields */
int NF; /* Number of fields */
char *fields[MAXFIELDS]; /* Pointers to fields */
int file; /* 1 for file, 0 for popen */
我不知道。使用调试器获取一些线索。至少它会立即给出触发seg故障的确切代码行。@kaylum我发现tmp变量为空,但为什么?我怀疑是缺少空字符造成的<代码>缓冲区不指向字符串。
const char *name; /* File name */
FILE *f; /* File descriptor */
int line; /* Line number */
char text1[MAXLEN]; /* The line */
char text2[MAXLEN]; /* Working -- contains fields */
int NF; /* Number of fields */
char *fields[MAXFIELDS]; /* Pointers to fields */
int file; /* 1 for file, 0 for popen */