Thread: Strcpy problem!!

  1. #1
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708

    Strcpy problem!!

    When I try:

    char *string;

    strcpy(string, "hello");

    ...It works.

    But when I do:

    char *strings[10];

    strcpy(strings[0], "hello");

    ...The program crashes.

    I know I can of course do:

    strings[0] = "hello";

    ...but in this application, the memory it will point to will be overwritten in later calls.

    Any ideas?
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  2. #2
    Registered User mlupo's Avatar
    Join Date
    Oct 2001
    Posts
    72
    what about if you just continue to do it this way?
    strcpy(string, "Hello")

    It worked for me and didn't crash.
    NEVER PET YOUR DOG WHILE IT'S ON FIRE!

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > char *string;
    > strcpy(string, "hello");
    > ...It works.
    string was unallocated, you were just being lucky
    Try it with char *string = NULL;
    Either way, it's wrong - you need to allocate memory before the strcpy

    > char *strings[10];
    > strcpy(strings[0], "hello");
    > ...The program crashes.
    Same dice - pointers are still uninitialised, just that this time you lost.


    > ...but in this application, the memory it will point to will be overwritten in later calls.
    strings[0] = malloc( strlen("hello") + 1 );
    strcpy ( strings[0], "hello" );
    Is the only way to go

  4. #4
    Sayeh
    Guest
    And remember, strcpy() is looking for the address of a dataspace, not an address to an address to a dataspace...

    Learn how to use '(' and ')' to help your compiler correctly build dereferencing statements.

  5. #5
    Registered User
    Join Date
    Oct 2001
    Posts
    197

    use strncpy() !!!!!!!

    Hi!

    Use the function strncpy()!
    So you can prevent a buffer-overflow!!

    klausi
    When I close my eyes nobody can see me...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What's up with this strcpy?
    By fanoliv in forum C Programming
    Replies: 7
    Last Post: 06-19-2006, 05:24 PM
  2. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM
  3. Replies: 5
    Last Post: 11-07-2005, 11:34 PM
  4. half ADT (nested struct) problem...
    By CyC|OpS in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 08:37 AM
  5. From stream/file to a string array problem
    By dradsws in forum C Programming
    Replies: 2
    Last Post: 10-01-2001, 06:24 PM