Probably just another silly pointer issue from a C newbie. Couldn’t figure this one out though. It seems that somehow my stack frame is corrupted. The assignment seems mostly irrelevant, but it’s a fairly basic I/O exercises. Attempting to read in an array of structures with a single read (cannot use advanced I/O functions such as 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);
}
I receive this error via 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) {
Thanks!
reads the number of countries as an argument to the program but you later hard-code the assumption that this is
>= 238when you callCan you try
instead? There are also a few errors in your
binary_searchfunction which could be re-written asThe main changes are
midtakes account oflas well asrstrcmp. Very minor but it makes the code clearer to me and will improve performance of searchesLess importantly, there are some stylistic issues that make your code hard to read
COUNTRY_COUNT) for variables is unusual. All upper case is often informally reserved for defines with variables using lower or camelCase