Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'strcpy' with 'malloc'?

Tags:

c

malloc

strcpy

Is it safe to do something like the following?

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

int main(void)
{
    char* msg;

    strcpy(msg, "Hello World!!!");  //<---------

    printf("%s\n", msg);

    return 0;
}

Or should the following be used?

char* msg = (char*)malloc(sizeof(char) * 15);
like image 541
LEH Avatar asked Mar 18 '11 16:03

LEH


People also ask

Does strcpy work on malloc?

The following example allocates space for a key using malloc() then uses strcpy() to place the key there. Then it allocates space for data using malloc(), and uses strcpy() to place data there. (The user-defined function dbfree() frees memory previously allocated to an array of type struct element *.)

Does strcpy copy memory?

No, strcpy knows nothing about memory, so your code copies a string into an uninitialized pointer pointing at la-la land.

Which is better strcpy or strncpy?

The strncpy function is a safer version of strcpy to copy a string from a source to a destination buffer. It takes three arguments, its third argument (n) is the maximum number of characters to copy.

Can you use strcpy with pointers?

strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string.


3 Answers

strdup does the malloc and strcpy for you

char *msg = strdup("hello world");
like image 171
pm100 Avatar answered Sep 19 '22 09:09

pm100


Your original code does not assign msg. Attempting to strcpy to it would be bad. You need to allocate some space before you strcpy into it. You could use malloc as you suggest or allocate space on the stack like this:

char msg[15];

If you malloc the memory you should remember to free it at some point. If you allocate on the stack the memory will be automatically returned to the stack when it goes out of scope (e.g. the function exits). In both cases you need to be careful to allocate enough to be able to copy the longest string into it. You might want to take a look at strncpy to avoid overflowing the array.

like image 44
qbert220 Avatar answered Sep 22 '22 09:09

qbert220


The first version is not safe. And, msg should be pointing to valid memory location for "Hello World!!!" to get copied.

char* msg = (char*)malloc(sizeof(char) * 15);
strcpy(msg, "Hello World!!!");
like image 26
Mahesh Avatar answered Sep 22 '22 09:09

Mahesh