John
John

Reputation: 13

C: control reaches end of non void function... Even though it returns int?

I"m writing a character device in C (for linux). I have this function:

static ssize_t
device_write(struct file *file,
     const char __user * buffer, size_t length, loff_t * offset)
{
    int i, fd = 0;
    int = bytes_written;

    fd = open(file, O_WRONLY);

    printk("device_write(%p,%d)\n", file, length);

    for (i = 0; i < length && i < BUF_LEN-1; i++)
        get_user(Message[i], buffer + i);

    bytes_written = write(fd,Message,i);
    Message[BUF_LEN-1] = '\0';
    /* return the number of input characters used */
    return bytes_written;
}

And when I compile I get error: control reaches end of non-void function. I've double checked that I'm compiling the right program, and it's driving me nuts.

Any help would be welcome.

Also, slightly unrelated, but is it possible to init a char buffer to a certain string (e.g. char buffer[1000] = "HELLO")?

Upvotes: 0

Views: 118

Answers (2)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

The function has many problems

  1. This is invalid

    int = bytes_written;
    

    Maybe you mean

    int bytes_written;
    
  2. You must check fd != -1, any code following open() will "potentially" cause a Invalid file descriptor error, because you have no guarantee that fd is a valid descriptor.

    And you can't even know whether the error was set or not, because

    1. You don't check whether write() succeeded.
    2. You don't check what is the value of errno after every call that can possible set it's value != 0, namely open() and write().
  3. This Message[BUF_LEN-1] = '\0'; is very likely wrong, it would be Message[i - 1] = '\0';

    And it seems logical to do

    memcpy(Message, buffer, length); 
    Message[length] = '\0';
    
  4. As commented by @zwol, you can't use open() or write() from kernel space.

Upvotes: 2

rost0031
rost0031

Reputation: 1926

int = bytes_written; shoud be int bytes_written; at least to fix your current error. There are likely others.

Upvotes: 0

Related Questions