可能只是C新手的另一個愚蠢的指針問題。無法弄清楚這一點。似乎我的堆棧框架已損壞。這個任務似乎大多不相關,但這是一個相當基本的I/O練習。嘗試讀取一次讀取的結構數組(不能使用高級I/O函數,如fread())。錯誤讀取變量,無法訪問內存地址X
#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) {
謝謝!
您不應該爲此輸入malloc – Eregrith
這是爲什麼?很想知道。 – user2004672
http://stackoverflow.com/questions/605845 – Eregrith