0

I have a int variable and I am trying to use copy_to_user(buf,intflag_obj,sizeof(int)) but its giving me segment fault. How to fix this

update

    static ssize_t mychardev_read(struct file *file, char __user *buf, size_t count, loff_t *offset)
    {
        int flag=10;
        wait_event_interruptible(wq, flag != 0);
        int *data =flag;
        size_t datalen = strlen(data);
        flag=0;

        printk("Reading device: %d\n", MINOR(file->f_path.dentry->d_inode->i_rdev));

        if (count > datalen) {
            count = datalen;
        }

        if (copy_to_user(buf,&data, count)) {
            return -EFAULT;
        }

        return count;
    }
user786
  • 3,902
  • 4
  • 40
  • 72
  • well would be nice to know how you pass the pointer to kernel and how you use it. BTW when you say segfault you mean oops? – OznOg Mar 27 '21 at 11:07
  • 2
    what is `flag+"hello"` ? – OznOg Mar 27 '21 at 11:36
  • @OznOg flag in int – user786 Mar 27 '21 at 11:38
  • I mean `flag+"hello"` is a pointer to nowhere when flag is more than 5... seems wrong – OznOg Mar 27 '21 at 11:39
  • @OznOg `int flag` I am trying to concatinate word hello with value of flag which is global – user786 Mar 27 '21 at 11:43
  • the is the problem, you add a int with a pointer to char, what do you expect it does? – OznOg Mar 27 '21 at 11:48
  • 1
    @666: "I am trying to concatinate word hello with value of flag which is global" - Expression `flag+"hello"` is definitely a **wrong way** for doing this. See [that question](https://stackoverflow.com/questions/5172107/how-to-concatenate-string-and-int-in-c) about proper ways for concatenate int and string. – Tsyvarev Mar 27 '21 at 12:16
  • @OznOg is there a way I can share the number assigned to int with copy_to_user? – user786 Mar 27 '21 at 13:28
  • What is wrong with `copy_to_user(buf,&flag, count)`? `copy_to_user` / `copy_from_user` can be viewed as special sort of `memcpy` function. So most receipts for `memcpy` are also applied to these functions. E.g. [that one](https://stackoverflow.com/a/26485948/3440745). – Tsyvarev Mar 27 '21 at 13:50
  • @Tsyvarev so u are saying `copy_to_user(buf,&flag,count)` is correct? – user786 Mar 27 '21 at 14:53

1 Answers1

0

Since you want to concatenate the value of flag with the word "hello", I guess you want the value of flag to be read as a string.

You can use a char [] variable and the snprintf function to construct the value to be read:

    char data[11 + sizeof("hello")];
    size_t datalen;

    snprintf(data, sizeof(data), "%dhello", flag);
    datalen = strlen(data);

    if (count > datalen) {
        count = datalen;
    }

    if (copy_to_user(buf, data, count)) {
        return -EFAULT;
    }

    return count;
Ian Abbott
  • 15,083
  • 19
  • 33