0
char* my_strdup(char* param_1){
    char *p;
    int n = sizeof(param_1);

    p = (char*)(malloc(sizeof(char)*n));
    int i = 0;
    while(i<n){
        p[i] = param_1[i];
        i++;
       
    }
    return p;

}

while is not brocked in the end how can i fix

enter image description here

  • 2
    Change `sizeof (param_1)` to `strlen(param_1) + 1`, which is the actual length of the string (including NUL `'\0'`) instead of the size of a `char *`. As a side note, make `param_1` a `const char *` instead because you're not modifying it. – mediocrevegetable1 Sep 23 '21 at 11:10
  • 1
    welcome to SO. `malloc` does not give any string at all. It just returns an address. And you are using wrong size for allocation. `sizeof param_1` only yields the size of a pointer which is probably not what you want. – Gerhardh Sep 23 '21 at 11:10

1 Answers1

1

sizeof(T) gives the amount of memory that an object of type T requires. If T is a variable, then the type of this variable is used.

With char* param_1, expression sizeof(param_1) gives you the memory that type char* requires, i.e. the size of a pointer. This is likely to be always 8 (the size a pointer needs on a 64bit machine). But it is definitely not the length of the string to which param_1 points to.

correct would be...

int n = strlen(param_1) + 1;

The + 1 is required, because every string needs an additional terminating character at the end. By +1, this is copied together with the actual content.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58