可能只是 C 新手的另一个愚蠢的指针问题。不过想不出来这个。似乎我的堆栈帧以某种方式损坏了。该作业似乎几乎无关紧要,但它是一个相当基本的 I/O 练习。尝试通过单次读取读取结构数组(不能使用高级 I/O 函数,例如 fread())。
#include "A2_Phase2.h"
void read_directory(Cdir directory[], int cnt)
{
int fd;
char filename[] = "RandomStructDir.bin";
fd = open(filename, O_RDONLY, S_IRWXU);
if (fd < 0)
perror(strcat(filename, " failed to open."));
if (read(fd, &(directory[0].code[0]), sizeof(Cdir) * cnt) < 0) {
perror(strcat(filename, " could not be accessed."));
}
close(fd);
}
int binary_search(Cdir directory[], char *key, int l, int r) {
int mid = (int) r / 2;
if (strncmp(key, directory[mid].code, 3) < 0)
return binary_search(directory, key, l, mid - 1);
else if (strncmp(key, directory[mid].code, 3) > 0)
return binary_search(directory, key, mid + 1, r);
else
return mid;
}
int main(int argc, char *argv[])
{
int COUNTRY_COUNT = atoi(argv[1]);
printf("%d", COUNTRY_COUNT);
Cdir *directory = (Cdir *) malloc(sizeof(Cdir) * COUNTRY_COUNT);
read_directory(directory, COUNTRY_COUNT);
binary_search(directory, "ZWE", 0, 238);
free(directory);
}
我通过 GDB 收到此错误:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400940 in binary_search (
directory=<error reading variable: Cannot access memory at address 0x7fffff7feff8>,
key=<error reading variable: Cannot access memory at address 0x7fffff7feff0>, l=<error reading variable: Cannot access memory at address 0x7fffff7fefec>,
r=<error reading variable: Cannot access memory at address 0x7fffff7fefe8>)
at A2_Phase2.c:19
19 int binary_search(Cdir directory[], char *key, int l, int r) {
谢谢!