[問題] command line argument 和 malloc的問題
我寫了一個 linked list 的程式
#include<stdio.h>
#include<stdlib.h>
struct cache_block
{
int access_type;
long address;
long replace_factor;
struct cache_block *next;
};
typedef struct cache_block *var;
int main(int argc, char *argv[])
{
var head=NULL,ptr=NULL,newptr=NULL;
int i = 0;
int nums_of_block = 256;
/*Create a link for cache block and initialize*/
for(i=0;i<nums_of_block;i++)
{
if(i==1)
{
printf("1newptr = %d\n",newptr->replace_factor);
printf("head = %d\n",head->replace_factor);
printf("head->next = %d\n\n",ptr->replace_factor);
}
newptr = (var)malloc(sizeof(var));
if(i==1)
{
printf("2newptr = %d\n",newptr->replace_factor);
printf("head = %d\n",head->replace_factor);
printf("head->next = %d\n\n",ptr->replace_factor);
}
newptr->access_type = 0;
newptr->address = 0;
newptr->next = NULL;
if(head == NULL)
{
newptr->replace_factor = 1;
ptr = head = newptr;
}
else
{
newptr->replace_factor = 2;
ptr->next=newptr;
ptr=newptr;
}
}
}
編譯以後發現一件很奇怪的事情
假設編譯後產生的執行檔是 cache
然後我執行時輸入:
C:\>cache
1newptr = 1
head = 1
head->next = 1
2newptr = -1254904723
head = 1
head->next = 1
但是我多打一個(含以上)的命令列參數就會出錯
C:\>cache 2
1newptr = 1
head = 1
head->next = 1
2newptr = 2138586278
head = 2088354651
head->next = 2088354651
發現錯誤發生在 newptr = (var)malloc(sizeof(var)); 的地方
但是為什麼呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.134.153.141
※ 編輯: fbukevin 來自: 220.134.153.141 (01/17 17:09)
推
01/17 18:02, , 1F
01/17 18:02, 1F
→
01/17 18:02, , 2F
01/17 18:02, 2F
→
01/17 18:03, , 3F
01/17 18:03, 3F
→
01/17 19:38, , 4F
01/17 19:38, 4F