Thread: Strcpy

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #11
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    There's no possibility to overwrite your buffer if you use it right.

    Here. Let's try something. Here's something I wrote quickly. Try to break it:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(int argc, char *argv[])
    {
    	char *szArgs = NULL;
    	size_t i, len = 0;
    	
    	for(i=0;i<(size_t)argc;i++)
    	{
    		len += strlen(argv[i]) + 1;
    	}
    	szArgs = malloc(len);
    	if(!szArgs)
    	{
    		fprintf(stderr, "Unable to allocate buffer of size &#37;d\n", len);
    		return 1;
    	}
    	strcpy(szArgs, argv[0]);
    	for(i=1;i<(size_t)argc;i++)
    	{
    		strcat(szArgs, " ");
    		strcat(szArgs, argv[i]);
    	}
    	printf("szArgs = %s\n", szArgs);
    	printf("len = %d\n", len);
    	for(i = 0;i < len;i++)
    	{
    		printf("szArgs[%2d] =\t[%3d][%c]\n", i, szArgs[i], szArgs[i]);
    	}
    	free(szArgs);
    	return 0;
    }
    You can't get this program to write past the boundaries of szArgs, unless I made a simple mistake, which can be corrected.

    Of interest, while you are pushing the n versions of the string functions to be safer, I believe Salem mentioned before that the '\0' is left off when using strncpy() if your destination length is less than your source length.

    That means you have to add the '\0' yourself in those cases, which just opens the door to more issues.
    Last edited by MacGyver; 12-12-2007 at 11:57 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A Full Program to analyze.
    By sergioms in forum C Programming
    Replies: 2
    Last Post: 12-30-2008, 09:42 AM
  2. Using strcpy() and arrays of structs
    By vital101 in forum C Programming
    Replies: 3
    Last Post: 04-26-2007, 09:04 PM
  3. Where is strcpy() defined? (Can't find in string.h ect)
    By Zero_Point in forum C++ Programming
    Replies: 6
    Last Post: 04-03-2006, 05:14 PM
  4. Question about strcpy
    By Kevinmun in forum C Programming
    Replies: 4
    Last Post: 11-02-2005, 11:00 PM
  5. strcpy
    By Luigi in forum C++ Programming
    Replies: 17
    Last Post: 02-16-2003, 04:11 PM