Thread: passing a static char * to a function

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    351

    passing a static char * to a function

    Hi there,

    in terms of memory is this:
    Code:
    ...
    my_function("this is static");
    ...
    my_function(char *string)
    {
     //do some stuff but don't free;
     ...
    }
    just as valid as this? (using same function above):
    Code:
    ...
    char *my_string;
    my_string = malloc(sizeof(char) * 20);
    strcpy(my_string,"this is not static");
    my_function(my_string);
    
    if(my_string != NULL){free my_string;}

  2. #2
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Yes, it's valid.

    TIP: check the return value of malloc before using it

  3. #3
    Registered User
    Join Date
    Aug 2002
    Posts
    351
    i can't use const because the function is used many times in the code with other malloc'ed character arrays.

    i was trying to find out if it was just as valid to pass a static string, given the chance, becuase it requires less code and less calls to malloc and free.

    therefore, more efficient?

  4. #4
    Registered User
    Join Date
    Aug 2002
    Posts
    351
    ahh,

    it doesn't matter if the char* has been malloc'ed, i cans till use const.

    i see...



    ..said the blind man.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of Cprogramming.com
    Replies: 48
    Last Post: 05-10-2007, 02:25 AM
  2. newbie needs help with code
    By compudude86 in forum C Programming
    Replies: 6
    Last Post: 07-23-2006, 08:54 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Passing structures... I can't get it right.
    By j0hnb in forum C Programming
    Replies: 6
    Last Post: 01-26-2003, 11:55 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM