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
85 views
in Technique[技术] by (71.8m points)

c - Repurposing allocated memory

I have a global array of strings with undefined lengths:

static char *array[1<<8];

Those strings will be replaced by other strings, with probably a different size. Every time a new string comes in and needs to be stored in the array, I have to do this:

free(array[i]);
array[i] = malloc(len);
strcpy(array[i], str);

Now it could happen that the old and the new string are very similar in size, and memory could just be reused. I believe that realloc() does reuse the allocated memory directly in such circumstances.

Is there a standard function like realloc() that does not copy the data?

Or does does it even mater performance wise, because of the free()/malloc() are somehow smart enough to reuse the memory of the latest free() directly if it fits?

I've found that. But the responses are not satisfying for me. Why is there no function in standard C library like realloc() without data copying?

question from:https://stackoverflow.com/questions/66067351/repurposing-allocated-memory

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

1 Reply

0 votes
by (71.8m points)
Waitting for answers

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

1.4m articles

1.4m replys

5 comments

56.9k users

...