Stack area and heap area in C language

 

A local variable is stored in the stack area, and the memory space is released after the function call ends.

#include "stdio.h";
#include "stdlib.h";

int *getNum(){
    int i = 100;
    return &i;
}

void main(){
    int *i = getNum();
    printf( " %d\n\r " ,i); // The memory has been released, the result is incorrect 
}

 

 

Second, the memory dynamically allocated by malloc (memory allocate) is in the heap area and needs to be manually released by calling free.

 The memory requested by malloc can only be released with free. If a local variable is released with free, an error will be reported.

#include "stdio.h";
#include "stdlib.h";

char * getColor(){
     void *str = malloc ( 4 );
     char *color = ( char * )str;
     *color++ = ' r ' ;
     *color++ = ' e ' ;
     *color++ = ' d ' ;
     *color = ' \0 ' ; // End of string 
    return ( char * )str;
}

void main(){
    char *color = getColor();
    printf("%s\n\r",color);
    free(color);
    printf( " %s\n\r " ,color); // The memory has been released, the result is incorrect 
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324443347&siteId=291194637