PDA

View Full Version : Memory allocation in C


alphapatrol
05-31-2010, 01:07 PM
Any advice how to allocate memory for unlimited (unknown) length of string?

Eg. Commandline asks user for some string. Once entered, program uses this string. Problem is that programmer must define expected string either statically by char str[size] or dynamically by pointer char *str and then malloc(size) << very simplified, just for an example purposes. But in both cases we need to know expected size of the string or set it to some expected MAX value.

But what if we don't know how long will be a string entered by user? How then we allocate necessary amount of memory if we don't know how much memory we'll need?

basilas
05-31-2010, 01:25 PM
Hello,
I'm not very good at C, though, ... I'd say in C there is no way for allocating memory dynamically :confused:, like in java etc. but look for the function
calloc() , which may partially fulfill your need....(Wish I could help You better...)


with regards....

oracleguy
05-31-2010, 10:14 PM
The short answer is you can't. You need to read into some sort of buffer that has a finite size. You need to allocate what you think is the maximum the user will enter.

Depending on what you are doing you can read in chunks and grow some 2nd buffer to fit whatever the user enters. You just want to minimize how many memory allocations you have to do.

abduraooft
06-01-2010, 08:48 AM
You need to allocate what you think is the maximum the user will enter.
How about having a single char varable and a char * variable and then repeatedly read the input characters using getchar() into that char variable? You could use the realloc() function in the same loop to extend the allocated space and then copy the characters one by one.

oracleguy
06-01-2010, 09:04 AM
How about having a single char varable and a char * variable and then repeatedly read the input characters using getchar() into that char variable? You could use the realloc() function in the same loop to extend the allocated space and then copy the characters one by one.

Yeah that is more or less what I was talking about when I mentioned reading in chunks. However I would realloc in chunks of 10-50 bytes depending on the overall average size to avoid dozens of memory allocations and potential copies. (realloc does a memcpy if it can't simply expand the allocated block.)