Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does memcpy() uses realloc()?

#inlcude <stdio.h>
#inlcude <stdlib.h>
#inlcude <string.h>

int main() {
    char *buff = (char*)malloc(sizeof(char) * 5);
    char *str = "abcdefghijklmnopqrstuvwxyz";

    memcpy (buff, str, strlen(str));

    while(*buff) {
        printf("%c" , *buff++);
    }

    printf("\n");

    return 0;
}

this code prints the whole string "abc...xyz". but "buff" has no enough memory to hold that string. how memcpy() works? does it use realloc() ?

like image 970
shan Avatar asked May 23 '11 04:05

shan


People also ask

Does realloc use memcpy?

As realloc is free to do the equivalent of a malloc, memcpy and free of the original memory, this can happen at unanticpated times.

How does memcpy work in C?

memcpy() function in C/C++ The function memcpy() is used to copy a memory block from one location to another. One is source and another is destination pointed by the pointer. This is declared in “string. h” header file in C language.

What is the use of realloc ()?

In the C Programming Language, the realloc function is used to resize a block of memory that was previously allocated. The realloc function allocates a block of memory (which be can make it larger or smaller in size than the original) and copies the contents of the old block to the new block of memory, if necessary.

What is the difference between memset and memcpy?

memset() is used to set all the bytes in a block of memory to a particular char value. Memset also only plays well with char as it's its initialization value. memcpy() copies bytes between memory. This type of data being copied is irrelevant, it just makes byte-for-byte copies.


1 Answers

Your code has Undefined Behavior. To answer your question, NO, memcpy doesn't use realloc. sizeof(buf) should be adequate to accomodate strlen(str). Anything less is a crash.

The output might be printed as it's a small program, but in real big code it will cause hard to debug errors. Change your code to,

const char* const str = "abcdefghijklmnopqrstuvwxyz";
char* const buff = (char*)malloc(strlen(str) + 1);

Also, don't do *buff++ because you will loose the memory record (what you allocated). After malloc() one should do free(buff) once the memory usage is over, else it's a memory leak.

like image 166
iammilind Avatar answered Sep 21 '22 17:09

iammilind