简体   繁体   English

malloc导致C中的分段错误

[英]malloc causes segmentation fault in C

I am setting a pointer to pointers like in the code above. 我正在设置指针,如上面的代码中所示。 The problem is that malloc is throwing a segmentation fault no matter what I have tried. 问题是无论我尝试过什么,malloc都会抛出一个分段错误。 Here is the code: 这是代码:

wchar_t **Words ;
int lc = lineCounter() ;
**Words = malloc( lc * sizeof(int)  ) ;
if (**Words == NULL) return -1 ;

The lineCounter function is just a function that returns the number of lines in a file. lineCounter函数只是一个返回文件中行数的函数。 So what I try to do is free some memory that is needed to save the pointers to lc number of words. 所以我尝试做的是释放一些内存,将指针保存到lc个单词。

Here is a visual representation of what I have in mind : 以下是我的想法:

在此输入图像描述

Let me explain your code line by line: 让我逐行解释你的代码:

wchar_t **Words ;

It is creating a pointer pointing to a pointer on wchar_t. 它正在创建一个指向wchar_t上指针的指针。 The thing is, at creation it is pointing on a random area in the memory so it may not be yours. 问题是,在创建时它指向内存中的随机区域,因此它可能不属于您。

*Words = malloc( lc * sizeof(int)  ) ;

This line dereferences the pointer and modify it's content. 此行取消引用指针并修改其内容。 You're trying to modify a memory area that doesn't belong to you. 您正在尝试修改不属于您的内存区域。

I think that what you want to do is: 我想你想做的是:

wchar_t **Words ;
int lc = lineCounter() ;
Words = malloc( lc * sizeof(wchar_t *)  ) ;
if (Words == NULL) return -1 ;

And then malloc all the dimensions in your array. 然后malloc你的数组中的所有维度。

EDIT: 编辑:

You may want to do something like that to correspond to your scheme: 您可能希望执行类似的操作以符合您的方案:

wchar_t **Words ;
int i = 0;

int lc = lineCounter() ;
Words = malloc( lc * sizeof(wchar_t *)  ) ;
if (Words == NULL) return -1 ;
while (i < lc)
{
  Words[i] = malloc(size_of_a_line * sizeof(wchar_t));
  if (words[i] == NULL) return -1;
  ++i;
}

A pointer refers to a storage location . 指针指的是存储位置 A variable is an example of a storage location . 变量存储位置的示例。

The * operator takes a pointer and gives you the storage location that the pointer refers to. *运算符采用指针并为您提供指针所指的存储位置。

words is a pointer; words是指针; it refers to a storage location of type pointer to wchar_t . 它指的是pointer to wchar_t的类型pointer to wchar_t的存储位置。 Since it is not initialized, it is undefined what storage location it refers to. 由于它未初始化,因此未定义它所指的存储位置。

Applying the * operator takes the pointer and produces the location it refers to; 应用*运算符获取指针并生成它所引用的位置; since you haven't said what location it refers to, writing to that location could do anything, including crash. 因为你没有说出它所指的位置,所以写入该位置可以做任何事情,包括崩溃。

You need to make the pointer words refer to a location before you assign something to *words . 在为*words指定内容之前,需要使指针words指向某个位置。

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

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