static vs malloc()

As we know, returning a local variable from a function results in a logical error (since the variable will go out of scope when the function ends). As a result we need to make it “immortal”. We can do this by using the static keyword, or by dynamically allocating the memory (normally through malloc).

One difference that comes to my mind, is that static will create only one instance of the variable, while mallo will create as many variables as the function is called. Assume we have this main, that assigns the “input1” in str1 and “input2” to str2.

#include <stdlib.h>
#include <stdio.h>
 
char* foo(char*);
 
int main(void)
{
    char* str1 = NULL;
    char* str2 = NULL;
     
    str1 = foo("input1");
     
    printf("str1 = %s\nstr2 = %s\n", str1, str2);
     
    str2 = foo("input2");
     
    printf("str1 = %s\nstr2 = %s\n", str1, str2);
     
    return 0;
}

Then we have the function that uses the keyword static.

char* foo(char* input)
{
    static char word[10];
    strcpy(word, input);
    return word;
}

Even though we call the function twice, the variable array word, is the same, in the first call and in the second call. Even if you call the function many times, the variable array word, will always be the same, just one array! As a result we get this output

str1 = input1
str2 = (null)
str1 = input2  <-- This got modificated too!
str2 = input2

Now, we are going to use dynamic allocation of the array word. This will create as many arrays as the times we call the function.

char* foo(char* input)
{
    char* word;
     
    word = malloc(strlen(input) + 1);
    /* Should check for null pointer here */
     
    strcpy(word, input);
    return word;
}

which gives the following output

str1 = input1
str2 = (null)
str1 = input1
str2 = input2

This code was developed by me, G. Samaras.

Have questions about this code? Comments? Did you find a bug? Let me know!😀
Page created by G. (George) Samaras (DIT)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s