#1
  1. Cast down
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    Sweden
    Posts
    321
    Rep Power
    12

    Buffer overflow protection


    Here is my string function, it does the same as strcpy, I want to protect against buffer overflow. str1 will just be a pointer, and Ill malloc the space I need inside the function.

    Code:
    void scpy(char *str1, char *str2)
    {
    	//Copy string1 into string2 
    	int x=0; 
    	str1=(char*)malloc(slen(str2)+1*sizeof(char)); 
    	
    	while(*str2 != '\0')
    		str1[x++] = *str2++; 
    	str1[x] = '\0'; 
    	return; 
    }
    
    use:
    char s[] = "Automatically parse URLs"; 
    char *g; 
    
    scpy(&g, s); 
    printf("%s\n", g); 
    free(g);
    What's wrong with this?
  2. #2
  3. jasondoucette.com
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2003
    Location
    Canada
    Posts
    378
    Rep Power
    12
    I cannot see any obvious errors after a quick scan. Perhaps your slen() function has errors. Try posting the smallest amount of code you can that shows your problem, and we can take a look.
  4. #3
  5. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,643
    Rep Power
    4248
    Should't this:
    str1=(char*)malloc(slen(str2)+1*sizeof(char));
    really be:
    str1=(char*)malloc((slen(str2)+1)*sizeof(char));

    Note the extra parens :).

    [edit] To be absolutely bulletproof, I would check str1 after the malloc() to ensure that the value is not NULL. Also, I would change the function type to return int instead of void and make it return success or failure this way. [/edit]

    [edit2] Just noticed that you're passing address of g from main() and trying to allocate g within scpy. In this case, your argument type for the first argument is incorrect, since you're passing the address of a char ptr variable. Oh, and man strdup() to save yourself the trouble of reinventing the wheel :)[/edit2]
    Last edited by Scorpions4ever; September 2nd, 2003 at 07:05 PM.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo