Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

c - 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

question from:https://stackoverflow.com/questions/65646468/typedef-char-pointer-allocation-of-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...