Search code examples
cstringruntime-error

Why is the following code with strings generating a bus error when called from a function?


I've figured this out but I thought I might post it here in case it should help someone else.

So I have this code which reads an arbitrary about of data from a file and prints out the first string it finds (terminated by null). It appears to work fine if I use the code directly in the function, but returning the string always seems to result in a bus error if I use the string after capturing the return value.

static char *read_string(FILE *obj_file, off_t offset, size_t size) {
char *strraw = load_bytes(obj_file, offset, size);
char* str = malloc(size);
strcpy(str, "");
for (int i = 0; i < size; i++) {
    if (strraw[i] == '\0') {
        strncpy(str, strraw, i + 1);
        break;
    }
}
free(strraw);
return str;

}

Elsewhere:

char *string = *read_string(obj_file, absoluteOffset, 1024);
printf("  The String: %s\n", string);
free(string);

If I comment out the printf it runs fine, but if I attempt to use it I get that bus error. This function is following a similar design for another function I made which does similar string work just without reading anything from a file.


Solution

  • The problem in the question above is that function called below was prefixed with a *.

    This resulted in the returned value being dereferenced (which was not my intention), the dereference of the returned value resulted in only a single character being returned which caused the bus error when it was attempted to be used with printf which expected a null terminated string but it only received a single character.

    The way this function should have been called is without the * as shown below.

    char *string = read_string(obj_file, absoluteOffset, 1024);
    printf("  The String: %s\n", string);
    free(string);