Sar*_*aya 1 c malloc free memory-management
我一直收到这个错误 vidprocess: malloc.c:2451: sYSMALLOc: Assertion (old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
在这一步我只释放一次内存:
DIR *dp;
struct dirent *ep;
dp = opendir (folder_input);
if (dp != NULL) {
while ( (ep = readdir (dp)) && MAXVIDS != 0 ) {
char *filename;
filename = malloc(sizeof(char) * strlen(ep->d_name));
strcpy(filename, ep->d_name);
int len = strlen(filename);
char *last_three = &filename[len-3];
char trailer_file_name[100];
int in_if = 0;
if (strcasecmp(last_three, "MOV") == 0) {
strcpy(trailer_file_name, ep->d_name);
MAXVIDS--;
in_if = 1;
}
else if (strcasecmp(last_three, "MP4") == 0) {
strcpy(trailer_file_name, ep->d_name);
MAXVIDS--;
in_if = 1;
}
free(filename);
Run Code Online (Sandbox Code Playgroud)
这是我唯一使用的地方free().如果我不使用这部分我没有得到上面的错误,所以我只是假设我因内存释放而得到一个错误,但我不明白为什么那是错的?
您没有为filename以下内容分配足够的内存:
filename = malloc(sizeof(char) * strlen(ep->d_name));
Run Code Online (Sandbox Code Playgroud)
这不会为终止空字节分配空间,您需要strlen(ep->d_name) + 1字节.另外,作为旁注,sizeof(char) == 1 总是如此.
此外,对于这种错误,一个好的内存调试器将为您节省大量时间.如果它适用于您的平台/拱门或其他类似工具,我建议像valgrind这样的东西.
通过超出分配的缓冲区,您可能会损坏用于malloc()执行其簿记的内部数据结构,这就是您看到崩溃的原因free().