What happens to memory after '\0' in a C string?

前端 未结 11 1696
难免孤独
难免孤独 2020-12-23 11:25

Surprisingly simple/stupid/basic question, but I have no idea: Suppose I want to return the user of my function a C-string, whose length I do not know at the beginning of th

11条回答
  •  一向
    一向 (楼主)
    2020-12-23 11:40

    You can certainly preallocate to an upperbound, and use all or something less. Just make sure you actually use all or something less.

    Making two passes is also fine.

    You asked the right questions about the tradeoffs.

    How do you decide?

    Use two passes, initially, because:

    1. you'll know you aren't wasting memory.
    2. you're going to profile to find out where
       you need to optimize for speed anyway.
    3. upperbounds are hard to get right before
       you've written and tested and modified and
       used and updated the code in response to new
       requirements for a while.
    4. simplest thing that could possibly work.
    

    You might tighten up the code a little, too. Shorter is usually better. And the more the code takes advantage of known truths, the more comfortable I am that it does what it says.

    char* copyWithoutDuplicateChains(const char* str)
        {
        if (str == NULL) return NULL;
    
        const char* s = str;
        char prev = *s;               // [prev][s+1]...
        unsigned int outlen = 1;      // first character counted
    
        // Determine length necessary by mimicking processing
    
        while (*s)
            { while (*++s == prev);  // skip duplicates
              ++outlen;              // new character encountered
              prev = *s;             // restart chain
            }
    
        // Construct output
    
        char* outstr = (char*)malloc(outlen);
        s = str;
        *outstr++ = *s;               // first character copied
        while (*s)
            { while (*++s == prev);   // skip duplicates
              *outstr++ = *s;         // copy new character
            }
    
        // done
    
        return outstr;
        }
    

提交回复
热议问题