u/Valuable_Moment_6032

how can i improve error handling in my code?

Hi! i am currently have this snippet of code:

char *shader_get_source(const char *shader_path) {
    if (!shader_path) {
        fprintf(stderr, "Shader error: invalid args\n");
        return NULL;
    }
  
    // open file in read only mode
    int shader_fd = open(shader_path, O_RDONLY, S_IRUSR | S_IWUSR);
    if (shader_fd == -1) {
        perror("Shader error");
        return NULL;
    }
  
    struct stat shader_stat;
    if (fstat(shader_fd, &shader_stat) == -1) {
        perror("Shader error");
        close(shader_fd);
        return NULL;
    }
    // printf("shader file size: %ld\n", shader_stat.st_size);
  
    char *shader_mmap =
        mmap(NULL, shader_stat.st_size, PROT_READ, MAP_PRIVATE, shader_fd, 0);
    if (shader_mmap == MAP_FAILED) {
        perror("Shader error");
        close(shader_fd);
        return NULL;
    }
  
    // close the file after mmap returned
    close(shader_fd);
  
    char *shader_src = malloc(sizeof(char) * shader_stat.st_size + 1);
    if (!shader_src) {
        fprintf(stderr, "Shader error: couldn't allocate space\n");
        return NULL;
    }
  
    // copy the file content to the allocated string
    memcpy(shader_src, shader_mmap, shader_stat.st_size);
    shader_src[shader_stat.st_size] = '\0';
    // printf("%s", shader_src);
  
    if (munmap(shader_mmap, shader_stat.st_size) == -1) {
        perror("Shader error");
        free(shader_src);
        return NULL;
    }
  
    return shader_src;
}

it just mmap's a file and store it as a NUL terminated string

is there a better way to handle errors? because there is a good chance i will forget to free something before returning because of an error and right now i am repeating myself a lot

reddit.com