Search code examples
cstringmemory-managementrealloc

Precise Dynamic Memory Allocation


I would like to dynamically allocate memory for an input string whose size is unknown at the time of input,with exact precision, i.e. if the string is "stack" I would like to allocate 6 bytes only.

I guess the only way is to keep on increasing the upper limit of the array depending on the input but I am unable to figure out the piece of code.


Solution

  • strdup() is your friend.

    char *p = strdup("stack");