-3
有一個表應該隨着確定的函數增長。每次表格滿時,函數addMemory被調用,使當前表格 - >表格大小加倍。但是,一切似乎都行得通,只是爲了測試程序,我評論了addMemory調用,所以我期待着一個分段錯誤,因爲沒有新的內存請求到操作系統,但它並沒有失敗,它實際上是將數據寫入malloc的內存空間旁邊,沒有任何錯誤。 我不知道爲什麼會發生這種情況?沒有malloc沒有分段錯誤
的代碼是在這裏:
int main(){
//user* newUser = (user*)malloc(BASE_SIZE*sizeof(user));
user* newUser = (user*)malloc(sizeof(user));
userTable* table = (userTable*)malloc(sizeof(userTable));
newUser->age = 1000;
table->length = 0;
table->table= newUser;
table->length++;
int i = 0;
int memlimit = 1000;
for(i = 1; i < memlimit; i++){
if(memZone(table->length-1) != memZone(table->length)){
//this is the line that asks for more memory
addMemory((void*)table,"userTable");
printf("mem pos =%i, age = %i\n",table->length,table->table[i-1].age);
}
table->table[i].age = (1000 + i);
table->length++;
}
printf("All memory have been successfully allocated \n");
int anything;
while(scanf("%i",&anything)){
reduceMemory((void*)table,"userTable");
printf("Age = %i \n",table->table[table->length - 1].age);
}
}
結構的定義是這些的:
typedef struct {
/* Username unique for this user in the system */
char username[25];
/* User name */
char name[100];
/* Age */
unsigned int age;
/* User city */
char city[128];
} user;
/* Table of users */
typedef struct {
/* Array of users */
user* table;
/* Number of registers in the table */
int length;
} userTable;
這是我正在尋找的答案,謝謝! – tomacco