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

标签 c pointers struct segmentation-fault malloc

正在解决我必须将数据从文件读取到结构中的问题。

文件的组织方式包括一个名称、几行以 # 和评级结尾的 ASCII 艺术字。这是一个例子

Sample Name
( S )
( S )
# 5

我的结构是这样设置的:

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

我的问题是,当我尝试为以下代码中的名称字符串动态分配内存时,我不断收到段错误:

/*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;
  }

我记下了上面代码中我认为错误的位置,因为一旦我添加了该行,我就开始明白了。

我基本上是将文本中的名称读入 nameBuffer(数组),然后使用 strcpy 将此名称复制到结构中。有关如何解决此问题的任何建议?

感谢您的关注。

我将在下面包含我的其余来源:

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

当你 malloc all 时,你也必须做这样的事情:

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

为了防止溢出你必须限制fscanf的长度,即:

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

1 确保您实际上已经将某些内容读入 nameBuffer。

此外,strcpy 不会填充——但您可能知道这一点。

关于c - 尝试为结构中的字符串分配内存时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10290483/

相关文章:

c++ - 结构内存分配中的 char*

c - 当文件未按预期 100% 填充时,无法使用 C 从二进制文件读取结构

c - 不使用数组查找均值、中位数

c - 将 0x00 覆盖到文件 C 中

c - OpenCV 可移植性

c - ESP 32 中断问题

c - 为什么 char*p[10] 被编译器认为是 char** p?

c - 在 GCC 中使用结构并出现错误

c# - 为什么使用隐式转换运算符的自定义结构上的 Assert.AreEqual 会失败?

c++ - 为具有 1 和 2 字节字符的字符集实现退格