Memcpy problem

char *a=NULL;

char *s=NULL; 

a=(char *)calloc(1,(sizeof(char))); 

s=(char *)calloc(1,(sizeof(char))); 

a="DATA"; 

memcpy(s,a,(strlen(a))); 

printf("%s",s);

Can you tell me why his seal is DATA½½½½½½½½ ■ ε ■ ???? How to print only DATA ?? thank

+3
source share
6 answers

strlen only considers characters without the terminator '\ 0'. Without this terminator, printf does not know the end of the line.

Solution: Tetsru (s, a, (StrLen (a) + 1));

+2
source

Lines in C end with a null character value (nul).

strlen returns the number of characters to zero.

So you are not copying zero.

printf continues, prints everything that is in memory after s until it reaches zero.

You also create a buffer of size 1, so you write data for everything after s, and you leak the memory of calloc'd into a before you set the letter.

s , , nul-, a s. - , C "DATA".

+6

, , , . calloc() .

, memcpy() , . strcpy().

DATA

puts("DATA");

, , //.

+2

1 , - , "DATA" ( 4 + \0, ).

a=(char *)calloc(1,(sizeof(char)));

5 :

a=(char *)calloc(5, (sizeof(char)));
+1

\0 DATA, printf() , .

memcpy strcat:

strcat(s, a);

.

, , :

calloc(1,sizeof(char)) 

! , , ! .

+1

a="DATA";

. "DATA" . , , ,

a=(char *)calloc(1,(sizeof(char))); 

char.

memcpy(s,a,(strlen(a)));

, ( "DATA" ) , s. , s char, 1 char - .

strlen(a) 4 ( "DATA" ) memcpy 4 char. , , C , "null" char ('\ 0') . "DATA" "D" "A" "T" "A" "0".

, , .

To copy strings, use strcpy(or strncpy) instead , it will also copy the string with its final zero byte. ( strcpyless "safe" because you can overflow the destination buffer).

But the biggest problem that I see here is that you reserve the only char only for (and you destroy it) and s, so DATA \ 0 does not fit anywhere.

+1
source

Source: https://habr.com/ru/post/1753299/


All Articles