无法访问malloc';超出第一个地址的内存

无法访问malloc';超出第一个地址的内存,c,malloc,dynamic-memory-allocation,C,Malloc,Dynamic Memory Allocation,在文件中读取时,内存会动态地分配给将放置文件内容的字符串。这是在函数内部完成的,字符串作为char**str传递 使用gdb,我发现在线路**(str+I)=fgetc(aFile)处产生seg故障 以下是$gdb a.out core的输出以及一些变量的值: Program terminated with signal SIGSEGV, Segmentation fault. #0 0x0000000000400bd3 in readFile (aFile=0x994010, str=0x7

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

使用gdb,我发现在线路
**(str+I)=fgetc(aFile)处产生seg故障

以下是
$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
以下是相关功能:

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;
}
int readFile(FILE*aFile,char**str)//将文件放入字符串中
{
int fileSize=0;
int i=0;
//计算文件字符串的长度
while(fgetc(aFile)!=EOF)
文件大小++;
//malloc为字符串提供足够的空间
*str=(char*)malloc(sizeof(char)*(fileSize+1+1));//一个表示null,一个表示额外空间
如果(!(*(str)))
printf(“错误:*str==NULL\n”);
//倒带()到文件的开头
倒带(文件);
//将文件放入字符串中
对于(i=0;i
为什么可以访问内存的开头(因为缺少更好的术语),但不能访问更多? **级的看似连续的内存与*级的非连续内存有什么区别


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

应该是
*(*str+i)
而不是
**(str+i)
。您已将内存分配给
*str
指针

在代码中,指向已分配内存块的指针是
*str
,而不是
**str
。因此,您需要设置
*(*str)+i)
,或者,等效地,
(*str)[i]

应该是*(*str+i),您应该被样式警察枪杀 首先使用类似于这种编码风格的任何东西

使用类似的模式

char*myStr=*str=(char*)malloc

*myStr[i]=字节

我已经给了你一个答案,但我想我应该指出一些重要的问题

除非您需要使用指针算法,否则绝对不需要代码中的所有循环,您可以这样做

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

  // count the length of the file string
  fseek(aFile, 0L, SEEK_END);
  fileSize = ftell(aFile);
  fseek(aFile, 0L, SEEK_SET);

  // malloc enough space for the string
  *str = malloc(fileSize + 1 + 1)); // one for null, one for extra space
  if (*str == NULL)
      return -1;    
  if (fread(*str, 1, fileSize, aFile) != fileSize)
      return -1;
  return 0;
}
并且总是
sizeof(char)==1
。对于文件的大小,您可以执行
ssize\t length;fseek(文件,0L,搜索结束);长度=ftell(一个文件);倒带(文件)