cstringmemorystack-based

CANNOT copying char into last address of char* ( string )?


i would like to copy data of char* to another last address of char*

illustration

var1 -> O
var2 -> K

first step

var1 -> OK
var2 -> K

copy var2 to var1

result

var1 -> OK

written code

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

void timpah(char *dest, char *src, int l_dest, int l_src)
{
    int i = 0;
    while(i < l_dest)
    {
        dest[l_dest+i] = src[l_src+i];
    i++;
    }
}

int main()
{

char res[2024];
res[1] = 0x4f;

char a[] = {0x4b};


timpah(res,a,1,1);

printf("%s [%d]\n",res,strlen(res));
return 0;
}

run

root@xxx:/tmp# gcc -o a a.c
root@xxx:/tmp# ./a
 [0]

question

why my code is not working ? or is there any function had exists already to perform these, but i haven't know it yet ?

thx for any attention


Solution

  • You aren't setting res[0] at any point. If res[0] contains \0 your string ends there. You are probably making things harder than they have to be; you can always use strncpy and strncat.