简体   繁体   English

程序正在运行,但是测试抛出分段错误

[英]Program is working,but test throws segmentation fault

I have to create a program using linked list concept. 我必须使用链表概念创建一个程序。 It works on ubuntu, ideone.com, but when I submit it to the university tester, it reports Segmentation fault/Bus error/Memory limit exceeded/Stack limit exceeded (one of the list). 它可以在ubuntu,ideone.com上运行,但是当我将其提交给大学测试人员时,它会报告分段错误/总线错误/超出内存限制/超出堆栈限制(列表之一)。

Probably, problem is memory deallocation because only DevCpp fall down, and it causes a piece of code where I use free. 问题可能是内存释放,因为只有DevCpp崩溃了,这会导致我使用free的一段代码。

So, I used Valgrind, but I can't understand very much, what is written in the log,but it's still writing "Invalid read of size 8" or Invalid write of size 8. And it's related to memory allocation(sizeof blocks is 8, but not always I suppose). 因此,我使用了Valgrind,但我不太了解日志中写了什么,但是它仍在写“大小为8的无效读取”或大小为8的无效写入。这与内存分配有关(sizeof块为8,但并非总是如此。 Further there is written -"ERROR SUMMARY: 76 errors from 48 contexts (suppressed: 2 from 2)" and "total heap usage: 20 allocs, 20 frees, 160 bytes allocated" (I consider that lines important). 进一步写了-“错误摘要:来自48个上下文的76个错误(禁止显示:2个中的2个错误)”和“堆总使用量:20个分配,20个释放,160个字节分配”(我认为这行很重要)。

Finally, there is piece of likely problematic code. 最后,有一段可能有问题的代码。

TITEM *borrowItem(const char *to)
{ 
    TITEM *newItem = (TITEM *)malloc(sizeof(newItem));
    newItem->m_Next = NULL;
    newItem->m_To=(char *)malloc(sizeof(to));
    strcpy(newItem->m_To,to);
    newItem->m_Cargo = NULL;
    return newItem;
}

I suppose that problem is in allocation already. 我想这个问题已经在分配中了。 This function is used for creating of new list item pointer. 此函数用于创建新的列表项指针。 Memory is freed here: 内存在这里释放:

void freeItem(TITEM *item)
{
    free(item->m_To);
    free(item);     
    return;    
}

m_To is string and m_Next is next item pointer. m_To是字符串,m_Next是下一个项目指针。

You can't copy a string like this: 您不能复制这样的字符串:

newItem->m_To=(char*)malloc(sizeof(to));
strcpy(newItem->m_To,to);

The value of sizeof(to) will be the number of bytes occupied by a pointer (4 or 8). sizeof(to)的值将是指针(4或8)占用的字节数。

You should either do this: 您应该这样做:

newItem->m_To = malloc(strlen(to) + 1);
strcpy(newItem->m_To,to);

Or use the library function strdup , which does essentially the same thing. 或使用库函数strdup ,其功能基本相同。

newItem->m_To = strdup(to);

Note that I also removed the cast to (char*) from the malloc call. 请注意,我还从malloc调用中删除了对(char*)malloc You should also remove the cast in your other malloc call. 您还应该删除其他malloc调用中的malloc If this is straight C, that is... 如果这是直线C,那就是...


Dipstick said: Correct but possibly incomplete. 量油计说:正确,但可能不完整。 Isn't the malloc of newItem also just allocating the size of the pointer. newItem的malloc也不只是分配指针的大小。

You should allocate your structure like this: 您应该像这样分配您的结构:

TITEM *newItem = malloc(sizeof(TITEM));

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

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