0

I just started in C and this is a beginner question. But is there any way to copy a string without allocating memory beforehand? I want to reproduce the strcopy function inbuilt in C with the same structure (char *strcpy(char *src, char *dest);). I got it to work with declaring the char pointer in the function itself and then returning it. It works also with the original structure as strcpy if I allocate the memory beforehand.

#include <stdlib.h>

char *strcopy(char *src, char *dest)
{
    int i = 0;
    while (src[i] != '\0')
    {
        dest[i] = src[i];
        i++;
    }
    dest[i] = '\0';
    return (dest);
}

int str_size(char *str)
{
    int i = 0;
    while (str[i] != '\0')
        i++;
    return (i);
}

int main(int argc, char **argv)
{
    char *src = argv[1];
    char *dest = (char*)malloc(str_size(src));
    dest = strcopy(src, dest);
    return (0);
}

So is it somehow possible to copy a string without allocating memory beforehand and without changing my function-head?

toni
  • 133
  • 1
  • 13
  • Copy it to what? There has to be some memory location you want to copy to. – interjay Mar 14 '21 at 14:11
  • 1
    Too short: you need `char *dest = malloc(str_size(src) + 1);` to allow for the terminator. You can use the non-standard `strdup()` but there is still memory allocation inside the function. – Weather Vane Mar 14 '21 at 14:11
  • So it is in no way possible to copy the string without allocating memory? Because it worked before with the `char *dest;` declaration in the strcopy function. @WeatherVane actually I dont need the `... str_size(src) + 1 ...` It worked fine just itself – toni Mar 14 '21 at 14:17
  • 1
    Yes you do: you need room for the null terminator `dest[i] = '\0';` Perhaps on some occasions `char *dest` happened to point to available memory, but it is still undefined behaviour. Appearing to be "working just fine" is one possible outcome. – Weather Vane Mar 14 '21 at 14:18
  • Oh im sorry, I changed my code, before it was `int i = 1;` Thats why it worked. – toni Mar 14 '21 at 14:20
  • You can have a static char array if you wanna avoid malloc. – Fredrik Mar 14 '21 at 14:27
  • 2
    Your question is similar to "Can I put eggs in a basket without having a basket first?" – William Pursell Mar 14 '21 at 14:39

1 Answers1

1

If you want to avoid dynamic allocation, use static allocation:

#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE        1024

char *strcopy(char *src, char *dest)
{
    int i = 0;
    while (src[i] != '\0')
    {
        dest[i] = src[i];
        i++;
    }
    dest[i] = '\0';
    return (dest);
}

int str_size(char *str)
{
    int i = 0;
    while (str[i] != '\0')
        i++;
    return (i);
}

int main(int argc, char **argv)
{
    char *src = argv[1];
    char dest[BUFFER_SIZE];
    
    if(strlen(src) >= BUFFER_SIZE){
        return -1;
    }
    else{
        dest = strcopy(src, dest);
    }

    return 0;
}
quent
  • 1,936
  • 1
  • 23
  • 28