memory allocation for strcpy

This is a discussion on memory allocation for strcpy within the C Programming forums, part of the General Programming Boards category; Hi all, Suppose i have a char variable pointer, and i allocated memory using malloc. is it different between using ...

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    18

    memory allocation for strcpy

    Hi all,

    Suppose i have a char variable pointer, and i allocated memory using malloc. is it different between using strcpy and assigned value directly to this pointer?
    Code:
    char *s1;
    s1 = (char *)malloc(80);
    
    s1 = "Test"                                 //assigned value directly to variable pointer S1
    strcpy(s1, "hallo")                      //using strcpy to copy "hallo" to s1
    in term of memory, are both use the same memory that has allocated by malloc ??

    thanks you for you answer

  2. #2
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    No it's not the same memory. If you need space for a string, use malloc.
    Once you've allocated memory for it, don't re-assign the pointer for example:

    Code:
    char *s1 = malloc(80);
    
    strcpy(s1, "hallo")                      //using strcpy to copy "hallo" to s1
    
    s1 = "Test"                                 // Here we would lose the address of the allocated memory...
    s1 will point to a memory location that you specify, so in your example, you've already lost the address of the allocated memory when you assigned "Test" to it, which by the way is inconsistent with what you're doing.

    btw: you don't need to cast the return value of malloc() in C.

  3. #3
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Your code demonstrates exactly why string literals should always be assigned to a const char * (or const char* if you are Elysia).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory allocation question
    By dakarn in forum C Programming
    Replies: 11
    Last Post: 12-01-2008, 11:41 PM
  2. Dynamic memory allocation.
    By HAssan in forum C Programming
    Replies: 3
    Last Post: 09-07-2006, 06:04 PM
  3. Dynamic memory allocation...
    By dicorr in forum C Programming
    Replies: 1
    Last Post: 06-24-2006, 04:59 AM
  4. C memory allocation to c++
    By markucd in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2005, 05:56 AM
  5. Understanding Memory Allocation
    By Ragsdale85 in forum C Programming
    Replies: 7
    Last Post: 10-31-2005, 08:36 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21