Is there a function(s) to copy a string into a new space in memory

114 Views Asked by At

If I want to copy the string "Best School" into a new space in memory in C programming, What statement(s) can I use to reserve enough space for it?

I have tried using this:

malloc(strlen("Best School") + 1)

And this also

malloc(sizeof("Best School"))
2

There are 2 best solutions below

0
chqrlie On

The simplest and safest way to allocate a block of memory and copy a null terminated string into it is:

    char *ptr = strdup("Best School");

strdup() is declared in <string.h>, has been part of the POSIX Standard since its inception and finally made it into Standard C as of C23. It is available on most systems and can be defined this way:

#include <stdlib.h>

char *strdup(const char *s) {
    size_t size = strlen(s) + 1;
    char *p = malloc(size);
    return p ? memcpy(p, s, size) : NULL;
}

Alternately, you could use malloc, strlen and strcpy directly:

malloc allocates a block memory of a given size. The memory is uninitialized, its contents are indeterminate, so if the allocation was successful, you must then copy the string into it, including the null terminator ('\0'). "Best school" is a null terminated string with 12 bytes: 11 characters plus a null terminator byte.

    // add 1 for the null terminator
    char *ptr = malloc(strlen("Best school") + 1);
    if (ptr) strcpy(ptr, "Best school");

And for string literals, you could even use sizeof:

    // sizeof includes the null terminator in a string literal
    char *ptr = malloc(sizeof "Best school");
    if (ptr) strcpy(ptr, "Best school");

But both of the above solutions are error prone because:

  • one can easily forget to allocate or copy the extra byte for the null terminator. This bug causes undefined behavior, but can go undetected for some time because of the allocation granularity: e.g. allocating 11 bytes for "Best school" may return a block of 16 bytes and the 12th byte may happen to be a null byte, especially if this memory has not been used before. This kind of undefined behavior is sly and will bite at the worst time.
  • the sizeof version only works for string literals! If you want to allocate a copy of a string you only have a pointer to, sizeof(ptr) will evaluate to the size of the pointer, not that of the string, leading to undefined behavior for all but the shortest strings. This solution works for the example in the question, but should be disregarded.

The recommended solution is strdup.

4
0___________ On

You need to allocate the memory and copy the original string. I would advice at the beginning (for educational purposes) to write all functions. Here is an example

size_t mystrlen(const char *str)
{
    char *end = str;
    if(str) while(*end) end++;
    return end - str;
}

void *mymemcpy(void *dest, const void *src, size_t len)
{
    if(dest && src)
    {
        const unsigned char *ucsrc = src;
        unsigned char *ucdest = dest;
        while(len--) *ucdest++ = *ucsrc++;
    }
    return dest;
}

char *mystrdup(const char *str)
{
    char *newstr = NULL;
    size_t len = 0;
    if(str)
    {
        len = mystrlen(str) + 1;
        newstr = malloc(len);
        if(newstr)
        {
            mymmemcpy(newstr, str, len);
        }
    }
    return newstr;
}