Thread: Strcpy woes!!!

  1. #1
    Registered User
    Join Date
    Aug 2012
    Posts
    24

    Strcpy woes!!!

    Okay in the following code
    Code:
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    
    
    struct mystruct
    {
    	int a;
    	char * string;
    };
    
    
    struct mystruct mystruct1; 
    
    
    int main()
    {
    	mystruct1.string=(char *)malloc(sizeof(char));
    	strcpy(mystruct1.string,"ljgls;dd");
    	printf("Here");
    	return 0;
    }
    For any string with length > 8, the program crashes. Someone please tell me why that happens!!
    Thanks!

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Technically, it can crash for any string with length greater than zero. The behaviour is undefined. You just got lucky (or unlucky, depending on your perspective) that the malloc() function with your compiler/library allocates a chunk of 8 in your code, since you specified a length of 1.

    Try multiplying the argument of malloc() by a value that exceeds the length of any string you want to copy to mystruct1.string plus one.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Aug 2012
    Posts
    24
    Oh! Thank you so much!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 06-19-2010, 07:42 AM
  2. MD2 woes
    By psychopath in forum Game Programming
    Replies: 9
    Last Post: 07-02-2005, 07:46 PM
  3. ASP.NET woes
    By nickname_changed in forum C# Programming
    Replies: 0
    Last Post: 03-20-2004, 04:34 PM
  4. Dll woes
    By Abiotic in forum Windows Programming
    Replies: 3
    Last Post: 11-09-2003, 11:32 AM
  5. GDI woes
    By cppdude in forum Windows Programming
    Replies: 4
    Last Post: 03-17-2002, 10:48 PM