user2268978
user2268978

Reputation: 1

error while free memory if we use memcpy

While using memcpy and free memory, free is giving a heap corruption. I don't understand why.

char *buff = malloc(20);
memset(buff,NULL,20);
strcpy(buff,"xvxvxvxxvx");
char*time =  malloc(20));
memset(time,NULL,20);//memcpy use
memcpy(time,buff,20);
free(time);//crashing here
return 0;

Upvotes: 0

Views: 2512

Answers (2)

Mayank
Mayank

Reputation: 2210

second argument of memset expects int but is is receiving NULL.

void *memset(void *s, int c, size_t n);

The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.

So you can use memset as memset(buff,0,20); now the program will not crash.

Upvotes: 0

Pubby
Pubby

Reputation: 53017

sizeof(20) is the size of an int. You probably intended malloc(20) for 20 chars.

Upvotes: 5

Related Questions