next up previous contents
Next: 實機練習題 Up: 記憶體管理 Previous: 記憶體動態配置   Contents   DYWANG_HOME

記憶體重新配置

  1. 重新配置記憶體函式 realloc() 及釋放記憶體函式 free() 範例:
    [dywang@dyw219 zzz]$ vim malloc2.c
    [dywang@dyw219 zzz]$ cat malloc2.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
    	char name[20];
    	char *description;
    
    	strcpy(name, "De-Yu Wang");
    
    	description = malloc( 10 * sizeof(char) );
    	if( description == NULL ) {
    		fprintf(stderr, "Error - unable to allocate required memory\n");
    		return 1;
    	} else {
    		strcpy( description, "CSIE CYUT");
    	}
    	description = malloc( 100 * sizeof(char) );
    	if( description == NULL ) {
    		fprintf(stderr, "Error - unable to allocate required memory\n");
    		return 1;
    	} else {
    		strcpy( description, "ChaoYang University of Technology");
    	}
    	printf("Name = %s\n", name );
    	printf("Description: %s\n", description );
    	free(description);
    
    	return 0;
    }
    
  2. 編譯
    [dywang@dyw219 zzz]$ gcc -o malloc2 malloc2.c
    
  3. 執行
    [dywang@dyw219 zzz]$ ./malloc2
    Name = De-Yu Wang
    Description: ChaoYang University of Technology
    



De-Yu Wang 2021-01-11