无法在第一个地址之外访问malloc的内存

Cha*_*les 2 c malloc dynamic-memory-allocation

读取文件时,将为放置文件内容的字符串动态分配内存.这是在函数内部完成的,字符串作为传递char **str.

使用gdb我发现在线路上产生了一个seg故障 **(str+i) = fgetc(aFile);

以下是$ gdb a.out core一些变量值的输出:

Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x0000000000400bd3 in readFile (aFile=0x994010, str=0x7ffd8b1a9338) at src/morse.c:59
59      **(str + i) = fgetc(aFile);
(gdb) print i
$1 = 1
(gdb) print **(str + 0)
$2 = 65 'A'
(gdb) print *(str + 0)
$3 = 0x994250 "A"
(gdb) print (str + 0)
$4 = (char **) 0x7ffd8b1a9338
(gdb) print **(str + 1)
Cannot access memory at address 0x0
(gdb) print *(str + 1)
$5 = 0x0
(gdb) print (str + 1)
$6 = (char **) 0x7ffd8b1a9340
Run Code Online (Sandbox Code Playgroud)

这是相关功能:

int readFile(FILE *aFile, char **str) // puts a file into a string
{
  int fileSize = 0;
  int i = 0;

  // count the length of the file string
  while(fgetc(aFile) != EOF)
    fileSize++;

  // malloc enough space for the string
  *str = (char *)malloc(sizeof(char) * (fileSize + 1 + 1)); // one for null, one for extra space
  if(!(*(str)))
    printf("ERROR: *str == NULL\n");

  // rewind() to the start of the file
  rewind(aFile);

  // put the file into a string
  for(i = 0; i < fileSize; i++)
    **(str + i) = fgetc(aFile);
  **(str + i - 1) = '\0';

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么可以访问内存的开头(因为没有更好的术语)而不是更多?**级看似连续的内存和*级别的非连续内存有什么区别?

其余的代码可以在GitHub上看到.

B.S*_*kar 7

它应该是*(*str+i)代替**(str+i).您已将内存分配给*str指针.