简体   繁体   English

尝试为结构中的字符串分配内存时出现分段错误

[英]segmentation fault when trying to allocate memory for a string in a struct

Working on a problem where I have to read data from a file into a struct. 解决必须将文件中的数据读取到结构中的问题。

The file is organized so that there is a name, a few lines of ASCII art terminated by a # and a rating. 该文件经过组织,以便有一个名称,几行ASCII图片(以#结尾)和一个等级。 Here is an example 这是一个例子

Sample Name
( S )
( S )
# 5

I have my struct set up like this: 我有这样的结构设置:

typedef struct
 {
   char* name;
   char* art;
   int rating;
 }CASE;

My problem is that I keep getting a segmentation fault when I try to dynamically allocate memory for the name string in the code below: 我的问题是,当我尝试为以下代码中的名称字符串动态分配内存时,我始终遇到segmentation fault

/*FPin is file pointer to the txt file and all is the array of structs*/
void readFile(FILE* FPin, CASE** all)
{ 
  CASE* walker = *all;
  int count = 0;
  char buffer[160];
  char* bufferPtr = buffer;
  char nameBuffer[100];

  /*Reads in the name*/

  while(fscanf(FPin, "%[^\n]", nameBuffer))
  {
    printf("string is %s\n", nameBuffer);
    walker->name = (char*)malloc(sizeof(char)*(strlen(nameBuffer+1)));  /*ERROR*/  
    strcpy(walker->name, nameBuffer);
  } 

  return;
  }

I made a note of where I believe the error to be in the code above because once I added that line, I started getting it. 我记下了我认为上面代码中的错误的位置,因为一旦添加了该行,便开始获取它。

I'm basically reading a name from a text into a nameBuffer (array) and then using strcpy to copy this name into the struct. 我基本上是从文本中读取一个名称到nameBuffer(数组)中,然后使用strcpy将此名称复制到该结构中。 Any advice on how to fix this? 有关如何解决此问题的任何建议?

Thanks for looking. 感谢您的光临。

I'll include the rest of my source below: 我将在下面包括我的其余资料:

int main (void)
{
  CASE* all;
  FILE* FPin;

  if((FPin = fopen("art.txt", "r")) == NULL)
  {
    printf("Error opening file.");
    exit(100);  
  }

  allocateStructMem(&all);
  readFile(FPin, &all);

  fclose(FPin);
  return 0;
}

void allocateStructMem (CASE** all)
{
  if((*all = (CASE*)malloc(sizeof(CASE)*1000)) == NULL)
    {
      printf("Fatal memory error!\n");
      exit(1);
   }

  return;
}

strlen(nameBuffer+1) strlen(nameBuffer + 1)

strlen(nameBuffer)+1

You also have to do something like this when you malloc all : 当您all分配时,还必须执行以下操作:

int allocateStructMem(CASE **all)
{
    /*  +----- Note. And no need to cast as malloc returns (void *)
        |                                           */
    if((*all = malloc(sizeof(CASE*) * 1000)) == NULL)

To prevent overflow you have to limit the length of fscanf , ie: 为了防止溢出,您必须限制fscanf的长度,即:

while (fscanf(FPin, "%99[^\n]", nameBuffer) == 1) {

The 1 ensure you have actually read something into nameBuffer. 1确保您已实际将某些内容读入nameBuffer。

Also strcpy does not pad – but you might know that. 而且strcpy不会填充-但您可能知道这一点。

将+1移到方括号之外是否有帮助?

walker->name = (char*)malloc(sizeof(char)*(strlen(nameBuffer)+1));  /*ERROR*/ 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM