Does memcpy() uses realloc()?
Asked Answered
I

4

7
#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() ?

Ingrained answered 23/5, 2011 at 4:40 Comment(0)
T
13

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.

Termination answered 23/5, 2011 at 4:45 Comment(6)
i want to use this buffer to hold a string in my real application. that string has no predefined length. it grows dynamically (appending some other strings...) when program is running. the solution that i found is allocating some big memory( ~1KB ).i want to know are there any different solutions other than this?. please help. thanks.Ingrained
@shan, then you can use realloc() (but not memcpy()) for that purpose.Termination
please, don't cast returns from malloc, in C this can hide nasty errorsKrumm
@Jens, I have copy pasted code from question. Some compiler gives error without typecasting.Termination
@iammilind: C++ compilers will warn, but standards-compliant C compilers must not.Heretofore
Yes, if you get a warning on that, this is a strong sign that something is wrong, either you are compiling C with a C++ compiler or you are not including the necessary header files.Krumm
C
9

You might be getting the whole string printed out, but it is not safe and you are writing to and reading from unallocated memory. This produces Undefined Behavior.

memcpy does not do any memory allocation. It simply reads from and writes to the locations you provide. It doesn't check that it is alright to do so, and in this case you're lucky if your program doesn't crash.

Carliecarlile answered 23/5, 2011 at 4:42 Comment(5)
Thanks for the answer. but, if i don't know the length of the string how i allocate enough memory? i want to make a buffer. i want to avoid writing to and reading from unallocated memory. what are the changes what i have to do in my code? please help ? thanksIngrained
@Ingrained - If you are calling memcpy, and you know how much memory you're going to copy, then you know how much memory you need to allocate. Use strlen to find the length of a string (it looks for the terminating null character).Carliecarlile
Yes, you use strlen, just as you did for your memcpy, except for one detail. The strlen function does not count the terminating null character. Thus in both the malloc and memcpy you need to use strlen(str)+1. Also, you don't need to multiply by sizeof(char) in the malloc. by definition sizeof(char) == 1.Whitton
i want to use this buffer to hold a string in my real application. that string has no predefined length. it grows dynamically (appending some other strings...) when program is running. the solution that i found is allocating some big memory( ~1KB ).i want to know are there any different solutions other than this?. please help. thanks.Ingrained
@Ingrained - In that case, yes often people will allocate a large string buffer, but if the potential length could be larger, you should use realloc to grow your buffer as necessary.Carliecarlile
Y
1

how memcpy() works?

Because you've invoked undefined behavior. Undefined behavior may work exactly as you expect, and it may do something completely different. It may even differ between different runs of the same program. It could also format your hard disk and still be compliant with the standard (Though of course that's unlikely :P )

Undefined behavior means that the behavior is literally not defined to do anything. Anything is valid, including the behavior you're seeing. Note that if you try to free that memory the C runtime of your target platform will probably complain. ;)

Yes answered 23/5, 2011 at 4:45 Comment(0)
W
1

No memcpy does not use malloc. As you suspected, you are writing off the end of of buff. In your simple example, that does no apparent harm, but it is bad. Here are some of the things that could go wrong in a "real" program:

  • You might scribble on something allocated in the memory following your buff leading to subtle (or not so subtle) bugs later on.
  • You might scribble on headers used internally by malloc and free, leading to crashes or other problems on your next call to those functions.
  • You might end up writing to an address that has not been allocated to your process, in which case your program will immediately crash. (I suspect this is what you were expecting.)

There are malloc implementations that put unmapped guard pages around allocated memory to (usually) cause the program to crash in cases like this. Other implementations will detect this, but only on your next call to malloc or free (or when you call a special function to check the heap).

Whitton answered 23/5, 2011 at 4:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.