Computer Scientist

Wednesday, 5 October 2011

Allocate memory in a function

I used to try to find some ways to allocate memory in a function. When other functions invoke this function with a null pointer as a parameter, this null pointer would be filled with some contents.

The most silly way to accomplish this task is like this:

void fill_function (void * pointer){
    pointer = (void *) malloc (certain length);

    pointer is filled with some contects;
}

void main () {
    int * file_content;
    fill_function(file_content);

    printf("", file_content);
}

Here, the most important thing which is ignored is the malloc function will allocate the memory in a certain position of the memory which is completely decided by malloc not the one on the left side of the equal symbol. If the file_content pointer is initialized with a number 5(assume that this is a memory address). The fill_function will not allocate the memory space from 5. The malloc will find another free place (for example 102, another memory address) and allocate the continuous memory space after 102, the local pointer variable pointer will be set to be 102. However, the invoking function main has no chance to catch this allocated address.

So a more reasonable way is like this:

int * fill_function (){
    int * pointer = (int *) malloc (certain length);

    return pointer;
}

void main(){
    int * file_content = fill_function();

    printf("", file_content);
}

Another problem is the garbage allocation collection problem. At this point, the boost::shared_ptr<> is encouraged to be used in this situation if you are programming by C++.

No comments:

Post a Comment