簡體   English   中英

返回c中的連續塊

[英]Return the contiguous block in c

我在堆中創建一個長度為32個字節的數組( char *charheap; ),並將所有元素初始化為\\0 這是我的主要功能:

int main(void) {
   char *str1 = alloc_and_print(5,  "hello");
   char *str2 = alloc_and_print(5,  "brian");
 }

 char *alloc_and_print(int s, const char *cpy) {
   char *ncb = char_alloc(s);// allocate the next contiguous block
   if (ret == NULL) {
    printf("Failed\n");
   } else {
    strcpy(ncb, cpy);
    arr_print();// print the array
  }
  return ncb;
 }

這是我實現的:

/char_alloc(s): find the FIRST contiguous block of s+1 NULL ('\0') 
characters in charheap that does not contain the NULL terminator
of some previously allocated string./

char *char_alloc(int s) {
 int len = strlen(charheap);
  for (int i = 0; i < len; i++) {
  if (charheap[0] == '\0') {
   char a = charheap[0];
   return &a;
 } else if (charheap[i] == '\0') {
   char b = charheap[i+1];
   return &b;
  }
 }
 return NULL;
}

預期輸出:( \\表示\\0

hello\\\\\\\\\\\\\\\\\\\\\\\\\\\
hello\brian\\\\\\\\\\\\\\\\\\\\\

該解決方案是完全錯誤的,我只是打印出兩個失敗的示例。 :(

實際上, char_alloc應該返回一個指向連續塊開始的指針,但是我不知道如何正確實現它。 有人可以給我提示或提示嗎?

您的函數正在返回一個指向局部變量的指針,因此調用者會收到一個指向無效內存的指針。 只需將指針返回到charheap ,這就是您想要的。

   return &charheap[0];   /* was return &a; which is wrong */

   return &charheap[i+1]; /* was return &b; which is wrong */

您的for循環使用i < len作為終止條件,但是,由於charheap已填充\\0 ,因此strlen()將返回大小0 您要遍歷整個charheap ,因此只需使用該數組的大小(本例中為32 )。

  int len = 32; /* or sizeof(charheap) if it is declared as an array */

上面的兩個修復應該足以使您的程序按您預期的方式運行(請參閱示例 )。

但是,您不會進行檢查以確保堆中有足夠的空間來接受分配檢查。 如果可用內存的開始與charheap的末尾之間的距離小於或等於所需的大小,則分配將失敗。 您可以通過將len設置為您願意檢查的最后一點來足夠容易地執行此操作,然后再知道沒有足夠的空間。

  int len = 32 - s;

最后,當您嘗試分配第三個字符串時,循環將跳過第一個分配的字符串,但將覆蓋第二個分配的字符串。 您的循環邏輯需要更改以跳過每個分配的字符串。 您首先檢查charheap的當前位置是否空閑。 如果不是,則將位置向前移動字符串的長度,再加上一個以跳過字符串的'\\ 0'終止符。 如果當前位置是免費的,則將其返回。 如果找不到空閑位置,則返回NULL

char *char_alloc(int s) {
  int i = 0;
  int len = 32 - s;
  while (i < len) {
    if (charheap[i] == '\0') return &charheap[i];
    i += strlen(charheap+i) + 1;
  }
  return NULL;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM