簡體   English   中英

內存分配懷疑類型指針指向char

[英]Memory allocation doubt with type pointer to char

該程序應該提示單詞中的字母數(稍后輸入),以便知道要分配多少空間。 它似乎工作正常,但是如果你分配的內存少於要存儲的單詞所需的內存似乎並不重要。 這是一個我必須糾正的錯誤,還是因為這是指向char(char *)的指針是如何工作的?

#include <stdio.h>
#include <stdlib.h>

int main() 
{
unsigned int a = 0;
printf("Enter the size of the word(0=exit) :");
scanf("%d",&a);
if(a==0){return 0;}
else
     {
      char *word = (char *)malloc(a*sizeof(char) + 1);
      if(word == NULL)
          {
           fprintf(stderr,"no memory allocated");
           return 1;
          }
      printf("Reserved %d bytes of space (accounting for the end-character).\nEnter your word: ", a*sizeof(char) + 1);
      scanf("%s", word);
      printf("The word is: %s\n", word);
     }

return 0;
}

好吧,我想我可能已經修好了,這樣一來,用valgrind運行就沒有顯示出之前顯示的錯誤。

char aux[]="";
  scanf("%s", aux);

  if(strlen(aux)>(a*sizeof(char) + 1))
     {
  fprintf(stderr,"Word bigger than memory allocated\nExiting program\n");
  return 1;
     }
  else
     {
      strcpy(word,aux);
      printf("The word is: %s\nAnd is %d characters long\n", word, strlen(word));
     }

現在我的疑問是:為什么我可以聲明一個空的char數組(char aux [] =“”),然后使用“額外”內存而沒有錯誤(在valgrind輸出中)還有char * aux =“”; 給我一個分段錯誤? 我是C編程的新手,所以如果這是明顯/愚蠢的問題,我很抱歉。 謝謝。

這似乎並不重要,但它確實 ,如果使用的不是分配,您將最終與緩沖區溢出結束更大的空間。 您當前的實現可能會分配比實際請求更多的內容,也可能不會。 您無法繼續該行為,從不訪問/使用未分配的內存。

根據定義, sizeof( char ) == 1

是的,您必須更正程序中的錯誤。

當您分配的內存少於您需要的內存,並且稍后訪問該“額外”內存時,程序將進入未定義的行為模式。 它似乎可以工作,或者它可能會崩潰,或者它可能會做任何意外的事情。 基本上,在寫入未分配的額外內存后, 沒有任何保證。

[更新:]

我建議從文件中讀取任意長度的字符串是以下代碼。 我不禁說它有點長,但由於標准C不提供一個很好的字符串數據類型,我不得不自己完成整個內存管理工作。 所以這里是:

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/** Reads a string from a file and dynamically allocates memory for it. */
int fagetln(FILE *f, /*@out*/ char **s, /*@out*/ size_t *ssize)
{
  char *buf;
  size_t bufsize, index;
  int c;

  bufsize = 128;
  if ((buf = malloc(bufsize)) == NULL) {
    return -1;
  }

  index = 0;
  while ((c = fgetc(f)) != EOF && c != '\n') {
    if (!(index + 1 < bufsize)) {
      bufsize *= 2;
      char *newbuf = realloc(buf, bufsize);
      if (newbuf == NULL) {
        free(buf);
        return -1;
      }
      buf = newbuf;
    }
    assert(index < bufsize);
    buf[index++] = c;
  }

  *s = buf;
  *ssize = index;
  assert(index < bufsize);
  buf[index++] = '\0';
  return ferror(f) ? -1 : 0;
}

int main(void)
{
  char *s;
  size_t slen;

  if (fagetln(stdin, &s, &slen) != -1) {
    printf("%zu bytes: %s\n", slen, s);
  }
  return 0;
}

通常(但不總是)分配緩沖區的溢出會在free緩沖區時導致崩潰。 如果你最后添加free(word) ,你可能會看到崩潰。

暫無
暫無

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

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