Thread: memory management>?

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    19

    memory management>?

    whats wrong with the following 2 programs? is it stricly a memory management problem which depends where u compile it?

    #include <iostream.h>
    #include <string.h>

    char *foo1()
    {
    char b[10];
    strcpy(b, "hello");
    char *str = b;
    return str;
    }

    char *foo2()
    {
    char b[10];
    strcpy(b, "goodbye");
    char *str = b;
    return str;
    }

    main()
    {
    char *a;
    char *b;
    a = foo1();
    cout << a << endl;
    b = foo2();
    cout << a << " " << b << endl;
    }

    and this one:

    #include <iostream.h>
    #include <string.h>

    main()
    {
    char *str;
    *str = 'x';
    cout << *str << endl;
    }

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Code:
    #include <iostream.h> 
    #include <string.h> 
    
    char *foo1()
    { 
    char *b = new char[10];
    strcpy(b, "hello"); 
    
    return b;
    } 
    
    char *foo2() 
    { 
    char *b = new char[10];
    strcpy(b, "goodbye"); 
    
    return b;
    } 
    
    main() 
    { 
    char *a; 
    char *b; 
    a = foo1(); 
    cout << a << endl; 
    b = foo2(); 
    cout << a << " " << b << endl; 
    }
    I think this should work

  3. #3
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    ..or if you don't need to modify the returned strings then you could return const char*'s to the string literals. As literals are allocated statically you wouldn't have to allocate memory -

    Code:
    #include <iostream>
    
    using namespace std;
    
    const char *foo1()
    { 
    	return  "hello";
    } 
    
    const char *foo2() 
    { 
    	return "goodbye";
    } 
    
    int main() 
    { 
    	const char *a; 
    	const char *b; 
    	a = foo1(); 
    	cout << a << endl; 
    	b = foo2(); 
    	cout << a << " " << b << endl; 
    	return 0;
    }
    zen

  4. #4
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,130
    Two different problems:

    problem 1: scope resolution

    In the function, you have a char array you write to.
    You return a pointer to it. When the function terminates,
    the array goes out of scope and is deleted as well. So
    your program is left with a pointer to something non-existant.

    problem 2: writing to a pointer without memory attached

    You write your 'x' to the first character your pointer is pointing to.
    Where is it pointing to ? You didn't specify, your variable isn't initialized, so it just points to some random space. Most likely this random space belongs to another program which is ........ed when you try to write into it's memory
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  5. #5
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    ...even then however you cannot assign one string to another as you try in main() with the lines:

    a = foo1();

    b = foo2();

    you must use strcpy() as you did within foo1() and foo2().

    Remember when you declare a char * it can be either a pointer to a single char or a pointer to the first char in a c_style string that can be used as a string. You can't tell which it is until you initialize it or assign memory to it. Pointers are very powerful and flexible entities, but they also require a lot of "work" by the programmer.

  6. #6
    Registered User
    Join Date
    Sep 2001
    Posts
    19

    another "?"

    when i run these programs (with the errors still intact) once on VC++ and the other on UNIX.. i get different error behaivors.. why is that?

    Raz

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > why is that?
    Programs only have to be consistent if they are correct.

    If the programs are broken, then absolutely anything can happen, ranging from apparently doing what you expect (despite the problems) to abruptly rebooting your machine.

  8. #8
    Registered User
    Join Date
    Sep 2001
    Posts
    412
    Originally posted by guest
    ...even then however you cannot assign one string to another as you try in main() with the lines:

    a = foo1();

    b = foo2();

    you must use strcpy() as you did within foo1() and foo2().

    Remember when you declare a char * it can be either a pointer to a single char or a pointer to the first char in a c_style string that can be used as a string. You can't tell which it is until you initialize it or assign memory to it. Pointers are very powerful and flexible entities, but they also require a lot of "work" by the programmer.
    Not necessarily; foo1/foo2 returns a pointer to a string (assuming it worked), so:

    a = foo1();

    simply aliases the string; it's perfectly legal, and perhaps better from a memory point of view -- if you allocate memory in foo1(), you don't want to lose the pointer to it (which is the only way you could free thet memory).

    The real problems are the ones nvoigt mentioned; with those solved, the program would work.

  9. #9
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    I love to learn new things. This may be yet another opportunity.

    This I knew was acceptable:

    char * ptr1;
    char * ptr2;
    char ch = 'A';
    ptr2 = &ch;
    ptr1 = ptr2;
    cout << *ptr1;//A is printed to screen.

    However I thought the following sequence was not acceptable for the reasons given where they are given:

    char * ptr3 = new char[10];
    //this declares ptr3 and assigns it memory for 10 char but
    //doesn't initialize ptr3.

    strcpy(ptr3, "hello");
    //this assigns a literal string to ptr3.
    //can't do this:
    //ptr3 = "hello";
    //since ptr3 has already been
    //declared and wasn't initialized at time of declaration.
    //if ptr3 had been declared and initialized all in one statement
    //like this:
    //char * ptr3 = "hello";
    //that's fine. but that is initialization, not assignment as
    //attempted six lines above

    char * ptr4;
    //declares a char * but can't tell pointer to what yet. could be
    //pointer to first element of a string or to a single char.


    ptr4 = ptr3;
    //can't assign strings (or other "routine" arrays for that matter),
    //can assign pointers to single char, and ptrs to other types of
    //variables, but NOT strings (or "routine" arrays).
    //therefore I think this is an error, irrespective of where or how
    //ptr3 is declared. Even if ptr4 were declared like this:
    //char * ptr4 = new char[10];
    //trying to assign ptr3, or any other string, to ptr4 using the
    //assignment operator = is not legal. You MUST use strcpy(),
    //or a variant, to "assign" c_style strings. Or so I thought.


    cout << *ptr4;
    //therefore this ain't going to print hello to the screen since code
    //will balk at above line.

    If nobody casts the magic tie breaker before I get access to my compiler I will try to compile similar code when I get the opportunity.
    Last edited by guest; 11-30-2001 at 12:34 PM.

  10. #10
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    //this assigns a literal string to ptr3.
    //can't do this:
    //ptr3 = "hello";
    //since ptr3 has already been
    //declared and wasn't initialized at time of declaration.
    //if ptr3 had been declared and initialized all in one statement
    //like this:
    //char * ptr3 = "hello";
    //that's fine. but that is initialization, not assignment as
    //attempted six lines above
    I think you're confusing arrays and pointers. ptr = "hello", will work because "hello" is a string literal that has an address. It is not being copied anywhere. ptr can point at this address when it's first introduced into a program or at any other time and can be reassigned to point at other string literals(or character arrays) with the assignment operator.

    If you where using an array -

    char arr[5]

    then arr is a constant pointer to a location in memory. If you want to copy a string literal into this memory you either have to do it at initialisation, or copy the characters in the string one by one (strcpy).

    char*' s can also be reassigned to point to the same location as another char* (ptr4 = ptr3), as the contents of memory aren't being copied (as you'd need to do with an array). Copying the contents of an array would create a seperate copy of the array in memory, whereas copying pointers just creates another variable that points to the same location.
    Last edited by zen; 11-30-2001 at 02:00 PM.
    zen

  11. #11
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    You're standing my world on it's head! Not that I haven't had similar experiences before, but still.

    In review for my benefit and your critique. Given:

    char * ptr;

    //the following won't work because ptr isn't having an
    //address assigned to it and it doesn't have any memory
    //to hold a non-literal string.
    cout << "enter a word";
    cin >> ptr;

    //this will work however because ptr is given the address of
    //the literal string by assingment
    ptr = "Harry Potter";

    //but is ptr now a "string" or a pointer? If it's a string can
    //you manipulate it like a string like this?

    int length = strlen(ptr);

    //OR

    char array[30];
    strcpy(array, ptr);

    //OR

    char array2[30] = "Mission Impossible";
    strcpy(ptr, array2);

    //clearly, you can assign memory to ptr using the new operator
    ptr = new char[80];

    //and now you can do this:
    strcpy(ptr, array2);

    //even if you couldn't before, correct? You can even do this
    //now, correct?
    cout << "enter a word";
    cin >> ptr;

    //but can you still do this?
    ptr = "Foolish Lies";

    //and now I'll put the tuckered out ptr to rest so it can be
    //used all over again, just like it was new
    delete [] ptr;
    ptr = NULL;

    And now for the big question: What was different about ptr when it pointed to the literal string versus when it pointed to
    the first char in the char array after being assigned memory
    via the new operator in the above sequence? Or maybe I
    should ask a different question. What's the difference
    between a literal string and c_style string variables as they
    relate to char pointers?

    I'll try to work it out on the compiler ASAP, too. Thanks for
    the stimulation.

  12. #12
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    //but can you still do this?
    ptr = "Foolish Lies";
    You could do that, but you'd want to de-allocate the memory that ptr previously pointed to.

    What's the difference
    between a literal string and c_style string variables as they
    relate to char pointers?
    A string literal is a non-modifiable C style string allocated as static data, whereas a a character array holding a C style string is in memory allocated on either the stack or heap and is modifiable (unless it's been declared const).

    You can use a pointer to access either types, but it is illegal to use a pointer to modify the contents of a string literal whereas you can use a pointer to modify the contents of an array. In strict C++ a string literal should be a const char* but this wasn't enforced as too much old code would break (if you try to modify a string literal the result is undefined).
    zen

  13. #13
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    Compiled my last bit of code. Works as promised. Continue to read replies. Continue to learn. Thanks for expanding my horizon.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 01-13-2008, 02:14 AM
  2. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  3. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  4. reading files into memory
    By bobthebullet990 in forum C Programming
    Replies: 3
    Last Post: 11-30-2005, 03:39 PM
  5. Shared Memory - shmget questions
    By hendler in forum C Programming
    Replies: 1
    Last Post: 11-29-2005, 02:15 AM