Search

copy string in kernel using kstrcpy

Creating copy of existing strings would require allocation of new memory and then assign the old string to new one. The multiple steps required to create a string copy can be done with the help of a single function in the kernel.



Ref: Kernel API

In the example below, we have created a proc entry to show the usage of the function. A call to read the proc entry creates a copy of the existing string in temp allcates it to the string called copy which we send as output of the proc entry.



Save the file as proc_read_copy.c and compile it using the following makefile.



Compile and load the module into kernel using.



To see the output, read the proc entry created by the module.




3 comments:

  1. Very nice examples, but shouldn't you release the allocated memory by using kfree? for both pointers: temp and copy. If you don't do that you will have memory leak in that process.

    ReplyDelete
    Replies
    1. Thank you for pointing it out.

      Delete
    2. Updated to use of array, copy is not allocated using kmalloc so we cant use kfree on it

      Delete