Thread: how to retain an allocated memory

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User creek23's Avatar
    Join Date
    Jun 2010
    Location
    Philippines
    Posts
    17

    how to retain an allocated memory

    I'm trying to make my own strcpy. A version of strcpy that will allow this,
    PHP Code:
    [code]
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    int main(void) {
        
    char *content1;
        
    char *content2 "hello world";
        
        
    printf("%s\n"content2);
        
        
    strcpy(content1content2);
        
        
    printf("%s\n"content1);
        
        return 
    0;
    }
    [/
    code
    Of course the app crashes upon strcpy attempt because content1 doesn't have memory allocated in it. It's why I wrote this function.
    PHP Code:
    [code]
    void my_strcpy(char *dest, const char *src) {
        
    dest = (char *) malloc(sizeof(strlen(src)));
        
        while(*
    src) {
            *
    dest++ = *src++;
        }
        *
    dest '\0';
    }
    [/
    code
    where I was hoping my_strcpy(content1, content2); would work as expected. But no. content1 is NULL;

    How do I retain the allocated memory in my_strcpy's dest parameter?

    One solution is to make my_strcpy a non-void function.
    PHP Code:
    [code]
    char *my_strcpy(char *dest, const char *src) {
        
    dest = (char *) malloc(sizeof(strlen(src)));
        
    char *destcpy dest;
        
        while(*
    src) {
            *
    dest++ = *src++;
        }
        *
    dest '\0';
        
        return 
    destcpy;
    }
    [/
    code
    But I would have to use content1 = my_strcpy(content1, content2);, and not as simple as my_strcpy(content1, content2); like strcpy does.

    How do I pass-by-reference and retain allocated memory?
    Last edited by creek23; 06-24-2010 at 09:40 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mutex and Shared Memory Segment Questions.
    By MadDog in forum Linux Programming
    Replies: 14
    Last Post: 06-20-2010, 04:04 AM
  2. pass by reference the allocated memory in heap
    By nik2 in forum C Programming
    Replies: 4
    Last Post: 03-20-2010, 12:55 PM
  3. Problems with shared memory shmdt() shmctl()
    By Jcarroll in forum C Programming
    Replies: 1
    Last Post: 03-17-2009, 10:48 PM
  4. Check if there is memory allocated
    By The Wazaa in forum C++ Programming
    Replies: 3
    Last Post: 04-23-2006, 05:48 AM
  5. Memory handler
    By Dr. Bebop in forum C Programming
    Replies: 7
    Last Post: 09-15-2002, 04:14 PM

Tags for this Thread