tags:

views:

112

answers:

4

Hi,

I can store string of few length in char data type.

But when it exceeds its capacity what can be the alternative way to store string.

I am using char data type.

void setString(char* inPoints)
{
if (strcmp(mPoints, inPoints)!= ZERO) {

    if (mPoints) {

        free(mPoints);
    }

    mPoints = (char*)malloc((strlen(inPoints) + 1)  * sizeof(char));

    strcpy(mPoints, inPoints);
}
}
+3  A: 

You can allocate a new, bigger array and copy the old string into it (and delete the old to prevent memory leaks), appending more characters. Or (if possible) switch to C++ string class, which makes this process easier.

PeterK
it is what his code already does, even though he could use realloc instead.
ShinTakezou
+2  A: 

realloc() should resize your string

OJW
it is what he already does, even though "by hand" instead of using realloc (which is anyway better solution).
ShinTakezou
A: 

Using strncpy instead of strcpy is normally safer, but here you alloc eachtime the right amount of memory needed to store inPoint into mPoint, so I cant see what's the point. The max length of a string you can store in mPoint is limited by the amount of malloc-able memory.

Add: you can realloc as suggested, and likely you can add a check on the length to avoid realloc-ing if the string is shorter; so mPoint would be able to hold always strings less than the longest string met so far, or equal to:


// somewhere altogether with mPoints
size_t mPointsCurrenStorage = INITVAL;
// e.g. INITVAL is 256, and you pre-malloc-ate mPoints to 256 chars
// ... in the func
size_t cl = strlen(inPoints);
if ( cl >= mPointsCurrentStorage ) {
  mPoints = realloc(mPoints, cl+1);
  mPointsCurrentStorage = cl+1;
}
strcpy(mPoints, inPoints);

this way the storage grows only...

ShinTakezou
of course I missed the test to avoid the realloc-copying if the string is the same of the one already stored. you can add it before doing anything else.
ShinTakezou
Avoid `p = realloc(p, size)`. If `realloc` fails, you've leaked your original pointer.
jamesdlin
yes it is not fine coding, but I used it just to show the point; so `char *temp = realloc(mPoints, cl+1); assert(temp != NULL); mPoints = temp` could be used instead; (changing assertion into any needed checking code of course if one does not like assertions)
ShinTakezou
`assert` is totally inappropriate for checking runtime failures.
jamesdlin
Thanks to all. It seems my code will improve a lot....
iSight
@jamesdlin : assert is appropriate for runtime failure (and it is what it is used for often!). the behaviour could be not the one the user wants (abort the prog abruptly if assertion is false), but it is not interesting here
ShinTakezou
assert() may be used often for checking runtime failures -- mostly by programmers who don't know what they are doing. http://en.wikipedia.org/wiki/Assertion_(computing) especially here: http://en.wikipedia.org/wiki/Assertion_(computing)#Comparison_with_error_handling
Secure
it is exactly the opposite and wiki page confirm that: it is mostly used by programmers who __know__ exactly what they are doing (and also by lazy programmers, by the way); reread what's written in the wiki page and answer, like `But if a graceful failure is desired, the program has to handle the failure`... here it is sample code, no need to require/desire failure handling; when used "there", programmer may be sure that if __that__ fails, there's no reason to continue or even stay, since something really odd and more serious happened in the system.
ShinTakezou
If you're so sure about this... I really hope you never compile your release versions with the macro NDEBUG defined...
Secure
smartness is made of smart choices. if I use assert as a "debug tool", I surely will define NDEBUG, exactly how I would strip any debuggin option. If I use it the other way, I won't use NDEBUG, or use more complicated self-written macros for finer control for debug and/or for preconditions and postconditions, whatever. What you're selling as a Great Programmer Truth (the Indiscriminate Evilness of Assertions) is none but Opinion About Programming Style.
ShinTakezou
I'm not selling anything to anyone. I'm telling my opinion, my knowledge and my experiences. You can believe me blindly or you can believe me not a single word. In fact I don't care at all what you do with it. But assert is a tool, and like most tools it was developed with a specific purpose in mind. Of course this is the software world, you can do nearly everything with everything. You can use assert for runtime checks, Excel as a database and you can do image editing with a hex editor. But I don't call it a "smart" choice to do so.
Secure
Telling ur opinion like a SuperiorOpinion,even worse than a Truth. There's no failure checking in my answercode. jamesdlin: overwriting p could be problematic...Oh,if realloc fails,the whole code can be problematic(no words about this);changing `p=realloc(p,n)` into `t=realloc(p,n);p=t` has sense?Ok you meant I had to write `t=..;if(t==NULL){/*graceful failure if desired/needed*/};p=t;`...undebatable by-design (and so wrong by definition)assertions about `assert` are uninteresting and totally inappropriate here.Showing usage of assert in __non-runtime failure__ would be(more)interesting.
ShinTakezou
A: 
  • strcmp with mPoints=NULL is not allowed.
  • ZERO as a constant?
  • free() accepts NULL pointers.
  • malloc() doesn't need a cast in C.
  • sizeof(char) is 1.
  • Always check the return of malloc().

Modified version:

void setString(char* inPoints)
{
    if ((mPoints == NULL) || (strcmp(mPoints, inPoints) != 0)) 
    {
        free(mPoints);

        mPoints = malloc(strlen(inPoints) + 1);

        if (mPoints != NULL)
        {
            strcpy(mPoints, inPoints);
        }
    }
}

And you're using a global variable mPoints, there are better solutions. But this and the error handling for malloc()=NULL aside, you're always allocating the needed amount, so what exactly do you mean by "exceeds its capacity"?

Secure
@Secure mPoints is private member.
iSight
There are no private members in C. What are you talking about?
Secure