This is the mail archive of the mailing list for the Cygwin project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

RE: malloc() question..

Keet / Foxbird wrote:
> the line that caused the problem. The baffling thing about this line is
> that it's the line that calls 'malloc'? It takes the length of a string,
> adds a few to it, mallocs the memory, and then assigns a string into it.
> This line is called many, many times before this, and works fine each time,
> but it seems to trip up after a certain number of calls. I've asked a few
> people what to do, and some told me it was some kinda of memory pointer
> problem, and that I should add 16 to all the malloc calls I make. Did that,
> and it progresses quite a bit farther but it then it drops out on another
> malloc call. So now I'm lost as to what to do. Can anyone offer any help?
> - Greg Neujahr
> /* Snippet of code that gets called too many times to count. */
> char *color_sub(char *qstring) {
>    char *holdstr;                 // Temporary array to hold the results
>    char escape[2], subval[6];     // escape=escape character; subval=value
> to sub
>    escape[0]=27;                  // Fisrt character=escape
>    escape[1]='\0';                // Make it a valid string
>    holdstr = (char *) malloc( strlen(qstring)+17 ); /* Allocate size for
> result. This line is normally +1 not +17 */
>    strcpy(subval,escape);        // Copy the escape string into the
> substitute string
>    strcat(subval,"[30m");        // Tack on ANSI sub value
>    holdstr = subst(qstring, subval, "%%00%%");      // Substitue ansi string
>    qstring = (char *) malloc(strlen(holdstr)+16);   // Allocate space for
> result
>    qstring = holdstr;            // Assign the result to the original string
> /* More code that looks almost exactly the same follows. subst() is a
> section that just substitutes out the %%??%% codes and turns them into Ansi
> escapes. Yes, the string has a positive length (and is not 0). */
>    return qstring;
> }

Looks to me as though the line:

    holdstr = subst(qstring, subval, "%%00%%");

is assigning to holdstr, rather than making use of the memory
previously allocated (unless you've redefined "=" for "char*" :)

and the same again with:

    qstring = holdstr;

looks like memory leak city. try some more strcpy()s.


For help on using this list (especially unsubscribing), send a message to
"" with one line of text: "help".

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]