Search code examples
cfilemallocvalgrind

Improve my C coding and find issues with code


I am new to coding in C and I am trying to figure out the problems my code may have to help me build safer code writing in C. Can anyone tell me what the problem with this code is? I know malloc here might fail because of memory leak. However is there any other problem with the code? and what's the best way of initialising fd? Please forgive me if this question is not strong enough.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main() {
    char *buffer;
    int lent = 0;
    //int i
    read(fd, &lent, sizeof(lent));
    if ((lent + 1) < 0) {
        error("negative length");
        return 0;
    }
    buffer = malloc(lent + 1);
    if (buffer == NULL) { 
        exit(EXIT_FAILURE);
    }
    read(fd, buffer, lent);
    buffer[lent] = '\0'; // null terminate buf
    return 0; 
}

Solution

  • I've put the issues in comments in the code.

    int main(){
        char *buffer;
        int lent=0;
        //int i
        read(fd, &lent, sizeof(lent)); // You never declare or set fd -- you need int fd = open("filename", O_RDONLY);
        if ((lent+1) < 0) { // This will allow lent == -1, even though that's negative
            error ("negative length"); // error() is not defined
            return 0;
        }
        buffer = malloc(lent+1);
        if (buffer==NULL) { 
            exit(EXIT_FAILURE);
        }
        read(fd,buffer,lent); // depending on what fd refers to, read() might return less than lent bytes, it returns how many bytes it read
        buffer[lent] = '\0'; // null terminate buf
        return 0; 
    }
    

    You should check the return values from read(), to make sure you didn't get an error or EOF.