<p>I've tried to write a string replace function in C, which works on a <code>char *</code>, which has been allocated using <code>malloc()</code>.  It's a little different in that it will find and replace strings, rather than characters in the starting string.</p>

<p>It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated.  If I try to use <code>realloc()</code>, I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using <code>realloc()</code>.</p>

<p>Perhaps a little code will help:</p>

<pre><code>void strrep(char *input, char *search, char *replace) {
    int searchLen = strlen(search);
    int replaceLen = strlen(replace);
    int delta = replaceLen - searchLen;
    char *find = input;

    while (find = strstr(find, search)) {

        if (delta &gt; 0) {
            realloc(input, strlen(input) + delta);
            find = strstr(input, search);            
        }

        memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input));
        memmove(find, replace, replaceLen);
    }
}
</code></pre>

<p>The program works, until I try to <code>realloc()</code> in an instance where the replaced string will be longer than the initial string.  (It still kind of works, it just spits out errors as well as the result).</p>

<p>If it helps, the calling code looks like:</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;stdlib.h&gt;

void strrep(char *input, char *search, char *replace);

int main(void) {
    char *input = malloc(81);

    while ((fgets(input, 81, stdin)) != NULL) {
        strrep(input, "Noel", "Christmas");
    }
}
</code></pre>

[{'answer_id': 1149, 'author': 'John Downey', 'author_id': 200, 'author_profile': 'https://Stackoverflow.com/users/200', 'pm_score': 3, 'selected': False, 'text': "<p>Just a shot in the dark because I haven't tried it yet but when you realloc it returns the pointer much like malloc. Because realloc can move the pointer if needed you are most likely operating on an invalid pointer if you don't do the following:</p>\n\n<pre><code>input = realloc(input, strlen(input) + delta);\n</code></pre>\n"}, {'answer_id': 1153, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 2, 'selected': False, 'text': "<p><strong>Note, try to edit your code to get rid of the html escape codes.</strong></p>\n\n<p>Well, though it has been a while since I used C/C++, realloc that grows only reuses the memory pointer value if there is room in memory after your original block.</p>\n\n<p>For instance, consider this:</p>\n\n<p>(xxxxxxxxxx..........)</p>\n\n<p>If your pointer points to the first x, and . means free memory location, and you grow the memory size pointed to by your variable by 5 bytes, it'll succeed. This is of course a simplified example as blocks are rounded up to a certain size for alignment, but anyway.</p>\n\n<p>However, if you subsequently try to grow it by another 10 bytes, and there is only 5 available, it will need to move the block in memory and update your pointer.</p>\n\n<p>However, in your example you are passing the function a pointer to the character, not a pointer to your variable, and thus while the strrep function internally might be able to adjust the variable in use, it is a local variable to the strrep function and your calling code will be left with the original pointer variable value.</p>\n\n<p>This pointer value, however, has been freed.</p>\n\n<p>In your case, input is the culprit.</p>\n\n<p>However, I would make another suggestion. In your case it looks like the <em>input</em> variable is indeed input, and if it is, it shouldn't be modified, at all.</p>\n\n<p>I would thus try to find another way to do what you want to do, without changing <em>input</em>, as side-effects like this can be hard to track down.</p>\n"}, {'answer_id': 1154, 'author': 'Vincent Robert', 'author_id': 268, 'author_profile': 'https://Stackoverflow.com/users/268', 'pm_score': 5, 'selected': True, 'text': "<p>As a general rule, you should <strong>never</strong> do a free or realloc on a user provided buffer. You don't know where the user allocated the space (in your module, in another DLL) so you cannot use any of the allocation functions on a user buffer.</p>\n\n<p>Provided that you now cannot do any reallocation within your function, you should change its behavior a little, like doing only one replacement, so the user will be able to compute the resulting string max length and provide you with a buffer long enough for this one replacement to occur.</p>\n\n<p>Then you could create another function to do the multiple replacements, but you will have to allocate the whole space for the resulting string and copy the user input string. Then you must provide a way to delete the string you allocated.</p>\n\n<p>Resulting in:</p>\n\n<pre><code>void  strrep(char *input, char *search, char *replace);\nchar* strrepm(char *input, char *search, char *replace);\nvoid  strrepmfree(char *input);\n</code></pre>\n"}, {'answer_id': 1155, 'author': 'Piotr Tyburski', 'author_id': 2090742, 'author_profile': 'https://Stackoverflow.com/users/2090742', 'pm_score': 0, 'selected': False, 'text': '<p>My quick hints.</p>\n\n<p>Instead of:<br>\n<code>void strrep(char *input, char *search, char *replace)</code><br>\ntry:<br>\n<code>void strrep(char *&amp;input, char *search, char *replace)</code></p>\n\n<p>and than in the body:<br>\n<code>input = realloc(input, strlen(input) + delta);</code></p>\n\n<p>Generally read about passing function arguments as values/reference and realloc() description :).</p>\n'}, {'answer_id': 1163, 'author': 'Mark', 'author_id': 263, 'author_profile': 'https://Stackoverflow.com/users/263', 'pm_score': 2, 'selected': False, 'text': '<p>This seems to work;</p>\n\n<pre><code>char *strrep(char *string, const char *search, const char *replace) {\n    char *p = strstr(string, search);\n\n    if (p) {\n        int occurrence = p - string;\n        int stringlength = strlen(string);\n        int searchlength = strlen(search);\n        int replacelength = strlen(replace);\n\n        if (replacelength &gt; searchlength) {\n            string = (char *) realloc(string, strlen(string) \n                + replacelength - searchlength + 1);\n        }\n\n        if (replacelength != searchlength) {\n            memmove(string + occurrence + replacelength, \n                        string + occurrence + searchlength, \n                        stringlength - occurrence - searchlength + 1);\n        }\n\n        strncpy(string + occurrence, replace, replacelength);\n    }\n\n    return string;\n}\n</code></pre>\n\n<p>Sigh, is there anyway to post code without it sucking?</p>\n'}, {'answer_id': 6405, 'author': 'Tryke', 'author_id': 773, 'author_profile': 'https://Stackoverflow.com/users/773', 'pm_score': 4, 'selected': False, 'text': '<p>First off, sorry I\'m late to the party. This is my first stackoverflow answer. :)</p>\n\n<p>As has been pointed out, when realloc() is called, you can potentially change the pointer to the memory being reallocated. When this happens, the argument "string" becomes invalid. Even if you reassign it, the change goes out of scope once the function ends.</p>\n\n<p>To answer the OP, realloc() returns a pointer to the newly-reallocated memory. The return value needs to be stored somewhere. Generally, you would do this:</p>\n\n<pre><code>data *foo = malloc(SIZE * sizeof(data));\ndata *bar = realloc(foo, NEWSIZE * sizeof(data));\n\n/* Test bar for safety before blowing away foo */\nif (bar != NULL)\n{\n   foo = bar;\n   bar = NULL;\n}\nelse\n{\n   fprintf(stderr, "Crap. Memory error.\\n");\n   free(foo);\n   exit(-1);\n}\n</code></pre>\n\n<p>As TyBoer points out, you guys can\'t change the value of the pointer being passed in as the input to this function. You can assign whatever you want, but the change will go out of scope at the end of the function. In the following block, "input" may or may not be an invalid pointer once the function completes:</p>\n\n<pre><code>void foobar(char *input, int newlength)\n{\n   /* Here, I ignore my own advice to save space. Check your return values! */\n   input = realloc(input, newlength * sizeof(char));\n}\n</code></pre>\n\n<p>Mark tries to work around this by returning the new pointer as the output of the function. If you do that, the onus is on the caller to never again use the pointer he used for input. If it matches the return value, then you have two pointers to the same spot and only need to call free() on one of them. If they don\'t match, the input pointer now points to memory that may or may not be owned by the process. Dereferencing it could cause a segmentation fault.</p>\n\n<p>You could use a double pointer for the input, like this:</p>\n\n<pre><code>void foobar(char **input, int newlength)\n{\n   *input = realloc(*input, newlength * sizeof(char));\n}\n</code></pre>\n\n<p>If the caller has a duplicate of the input pointer somewhere, that duplicate still might be invalid now.</p>\n\n<p>I think the cleanest solution here is to avoid using realloc() when trying to modify the function caller\'s input. Just malloc() a new buffer, return that, and let the caller decide whether or not to free the old text. This has the added benefit of letting the caller keep the original string!</p>\n'}, {'answer_id': 220594, 'author': 'Jonathan Leffler', 'author_id': 15168, 'author_profile': 'https://Stackoverflow.com/users/15168', 'pm_score': 3, 'selected': False, 'text': "<p>Someone else apologized for being late to the party - two and a half months ago.  Oh well, I spend quite a lot of time doing software archaeology.</p>\n\n<p>I'm interested that no-one has commented explicitly on the memory leak in the original design, or the off-by-one error.  And it was observing the memory leak that tells me exactly why you are getting the double-free error (because, to be precise, you are freeing the same memory multiple times - and you are doing so after trampling over the already freed memory).</p>\n\n<p>Before conducting the analysis, I'll agree with those who say your interface is less than stellar; however, if you dealt with the memory leak/trampling issues and documented the 'must be allocated memory' requirement, it could be 'OK'.</p>\n\n<p>What are the problems?  Well, you pass a buffer to realloc(), and realloc() returns you a new pointer to the area you should use - and you ignore that return value.  Consequently, realloc() has probably freed the original memory, and then you pass it the same pointer again, and it complains that you're freeing the same memory twice because you pass the original value to it again.  This not only leaks memory, but means that you are continuing to use the original space -- and John Downey's shot in the dark points out that you are misusing realloc(), but doesn't emphasize how severely you are doing so.  There's also an off-by-one error because you do not allocate enough space for the NUL '\\0' that terminates the string.</p>\n\n<p>The memory leak occurs because you do not provide a mechanism to tell the caller about the last value of the string.  Because you kept trampling over the original string plus the space after it, it looks like the code worked, but if your calling code freed the space, it too would get a double-free error, or it might get a core dump or equivalent because the memory control information is completely scrambled.</p>\n\n<p>Your code also doesn't protect against indefinite growth -- consider replacing 'Noel' with 'Joyeux Noel'.  Every time, you would add 7 characters, but you'd find another Noel in the replaced text, and expand it, and so on and so forth.  My fixup (below) does not address this issue - the simple solution is probably to check whether the search string appears in the replace string; an alternative is to skip over the replace string and continue the search after it.  The second has some non-trivial coding issues to address.</p>\n\n<p>So, my suggested revision of your called function is:</p>\n\n<pre><code>char *strrep(char *input, char *search, char *replace) {\n    int searchLen = strlen(search);\n    int replaceLen = strlen(replace);\n    int delta = replaceLen - searchLen;\n    char *find = input;\n\n    while ((find = strstr(find, search)) != 0) {\n        if (delta &gt; 0) {\n            input = realloc(input, strlen(input) + delta + 1);\n            find = strstr(input, search);            \n        }\n\n        memmove(find + replaceLen, find + searchLen, strlen(input) + 1 - (find - input));\n        memmove(find, replace, replaceLen);\n    }\n\n    return(input);\n}\n</code></pre>\n\n<p>This code does not detect memory allocation errors - and probably crashes (but if not, leaks memory) if realloc() fails.  See Steve Maguire's 'Writing Solid Code' book for an extensive discussion of memory management issues.</p>\n"}, {'answer_id': 6024343, 'author': 'Tom Andersen', 'author_id': 69948, 'author_profile': 'https://Stackoverflow.com/users/69948', 'pm_score': 2, 'selected': False, 'text': '<p>realloc is strange, complicated and should only be used when dealing with lots of memory lots of times per second. i.e. - where it actually makes your code faster. </p>\n\n<p>I have seen code where </p>\n\n<pre><code>realloc(bytes, smallerSize);\n</code></pre>\n\n<p>was used and worked to resize the buffer, making it smaller. Worked about a million times, then for some reason realloc decided that even if you were shortening the buffer, it would give you a nice new copy. So you crash in a random place 1/2 a second after the bad stuff happened. </p>\n\n<p>Always use the return value of realloc. </p>\n'}]
['https://Stackoverflow.com/questions/1145', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188/']