You are here:

C/C - dynamic memory

Advertisement


Question
Hi,

I have a another question. I know that by using malloc and relloc you can assign memory to a variable pointer but you have to know the size before hand. What if you don't?

I'm trying to write a simple function that accepts a string from the user and store it in a location. But the string can be anywhere from 0 - infinty.
How do you allocate dynamic memory at runtime? or how do you find out the length of the inputted string without storing it first (is that possible?)?

Thanks

Answer
Make a initial guess (or calculate) and allocate using malloc().
In the loop when the string is growing infinitely, you will know by how much amount it will grow each time.
So, add that to the current size and use realloc() to extend the allocation.
By using this strategy, you can go on increasing the size till your memory is exhausted:-)

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.