排序由指针组成的结构数组时出现分段错误
Segmentation fault while sorting structure array made of pointer
可能重复:
如何在C++程序中找到segfault?
排序结构时出现分段错误这是我的结构
typedef struct
{
char *id;
char *timestamp;
char *name;
char *text;
}DATA;
DATA *the_array = NULL;
我使用malloc和realloc动态分配内存。现在我使用bubblesort对这个结构进行排序。我在Windows7下使用流血c/c++ide。在我得到异常的地方添加代码。
for(int i =0;i < num_elements;i++)
{
if(strcmp("DUP",the_array[i].id)==1)
for(int j = i+ i; j < num_elements; j++)
{
if(strcmp("DUP",the_array[j].id)==1){
float n1 = strtof(the_array[i].timestamp,NULL);
float n2 = strtof(the_array[j].timestamp,NULL);
// Exchange the elements
if(n1 > n2)
{
// Exchange the id
temp_id = (char*)malloc(sizeof(the_array[i].id));
strcpy(temp_id,the_array[i].id);
strcpy(the_array[i].id,the_array[j].id);
strcpy(the_array[j].id,temp_id);
//Exchange the timestamps
temp_timestamp = (char*)malloc(sizeof(the_array[i].timestamp));
strcpy(temp_timestamp,the_array[i].timestamp);
strcpy(the_array[i].timestamp,the_array[j].timestamp);
strcpy(the_array[j].timestamp,temp_timestamp);
//Exchange the username
temp_username = (char*)malloc(sizeof(the_array[i].name));
strcpy(temp_username,the_array[i].name);
strcpy(the_array[i].name,the_array[j].name);
strcpy(the_array[j].name,temp_username);
//Exchange the text
temp_text = (char*)malloc(sizeof(the_array[i].text));
strcpy(temp_text,the_array[i].text);
strcpy(the_array[i].text,the_array[j].text);
strcpy(the_array[j].text,temp_text);
}
}
}
}
我能像这个一样做吗
for(int i =0;i < num_elements;i++)
{
if(strcmp(dup,the_array[i].id)==1)
for(int j = i+ i; j < num_elements; j++)
{
float n1 = strtof(the_array[i].timestamp,NULL);
float n2 = strtof(the_array[j].timestamp,NULL);
// Exchange the elements
if(n1 < n2)
{
//Change the pointer locations
temp_array1 = &the_array[i];
temp_array2 = &the_array[j];
temp_array3=temp_array1;
temp_array1=temp_array2;
temp_array2=temp_array3;
}
}
}
复制元素时,例如malloc
和sizeof(the_array[i].name))
,这是一个字符指针的大小。如果名称超过3个字节,则在复制到其中时会覆盖未分配的内存。您需要分配strlen(the_array[i].name)+1
。其他元素也是如此。即便如此,你也会遇到这样的问题,即节点X中的名称可能比你复制到其中的节点Y中的名称短。整个策略注定会失败。
您不交换节点是不是有什么原因?或者做得更好qsort(list, N, sizeof(DATA), DataTimestampCompare);
交换无序数组元素的代码有几个问题。您的问题同时标记为C
和C++
,但在C++
中,您可以简单地说:
// Exchange the elements
if(n1 > n2)
{
std::swap(the_array[i], the_array[j]);
}
您只需要交换结构或它们所包含的指针。您现有的代码没有为(不必要的)字符串复制分配足够的内存,并且存在严重的内存泄漏。
如果不了解如何进行分配和使用数组,将很难回答,但很可能您只是为结构分配内存,而忘记了成员指针。你也必须为它们分配内存,否则如果你试图访问其中的一些,你会遇到seg错误。
例如,如果只为"the_array"分配内存,*the_array->name
将导致seg故障。我猜你的排序算法试图访问结构的一些属性。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?