Search code examples
cstringpointersmallocdynamic-memory-allocation

Typedef char pointer allocation of string


I am trying to understand a code that has the typedef char * I am supposed to allocate memory enough for the string "Pointer of" and "Redundancy".

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

typedef char* DString;
DString dstring_initialize(const char* str);

int main(void)
{
    DString str1, str2;
    str1 = dstring_initialize("Pointer of ");
    str2 = dstring_initialize("Redundancy ");
return 0;
}

DString dstring_initialize(const char* str)
{
  str = malloc((strlen(str)+1)*sizeof(DString));//mycode 
  return str;//mycode
}

I am 100% sure that I am doing it completely wrong. The only thing I am supposed to do is change the part where it says mycode. It was sent to me like that, but as I said before, I don't know how it works, and if someone could explain it to me in detail, I would appreciate it


Solution

  • In the code below you allocate too much memory:

    str = malloc((strlen(str)+1)*sizeof(DString));//mycode 
                                 ^^^^^^^^^^^^^^
                                 Not needed
    

    Also you assign the return value from malloc to the input argument, i.e. you "destroy" the input.

    Further, you never copy the value of the input string to the allocated memory.

    Instead of the above, you need:

    char* res = malloc(strlen(str) + 1);
    if (res != NULL)
    {
        strcpy(res, str);
    }
    return res;