Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

memory leak

Name: Anonymous 2006-04-01 20:07

typedef char* String;

String getNth(String str, int n)
{
    int i;
    String temp = malloc(sizeof(char) * MAX_SIZE);
    String regExp = malloc(sizeof(char) * MAX_SIZE);
       
    for(i = 0; i < n; i++)
    {
        if (i == n-1) strcat(regExp, "%s");
        else strcat(regExp, "%*s");
    }

    sscanf(str, regExp, temp);
    free(regExp);
    return temp;
}

this leaks memory (temp). a neat way to prevent this, please.

Name: Anonymous 2009-11-01 17:38

typedef char* String;

void getNth(String dest, String str, int n)
{
    int i;
    String temp = malloc(sizeof(char) * MAX_SIZE);
    String regExp = malloc(sizeof(char) * MAX_SIZE);

    memset(temp, 0, sizeof(char) * MAX_SIZE);
    memset(regExp, 0, sizeof(char) * MAX_SIZE);

    /* what the hell is this? nobody knows.
     * please use real variable names and
     * comments in the future.
     */
    for(i = 0; i < n; i++)
    {
        if (i == n-1) strcat(regExp, "%s");
        else strcat(regExp, "%*s");
    }

    sscanf(str, regExp, temp);

    strcpy(dest, temp);

    free(temp);
    free(regExp);
    return temp;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List