首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

关于malloc的出现非内存空间不足的有关问题

2013-12-05 
关于malloc的出现非内存空间不足的问题#include header.h#include sys/stat.h#include sys/types.h#

关于malloc的出现非内存空间不足的问题
#include "header.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>

char* filelist[];
int filecount = 0;

int listfile(char *pathname){

if (pathname == NULL)
return -1;
struct stat statbuf;
struct dirent *dirp;
DIR *dp;
char dir[256];

if ((dp = opendir(pathname)) == NULL){
fprintf(stderr, "can not open directory: %s\n",pathname);
return -1;
}
while ((dirp = readdir(dp)) != NULL){
snprintf(dir,256, "%s/%s", pathname, dirp->d_name);
lstat(dir, &statbuf);
if (S_ISDIR(statbuf.st_mode)){
if (strcmp(".", dirp->d_name) == 0 || strcmp("..", dirp->d_name) == 0)
continue;
listfile(dir);
}
else {
if (S_ISREG(statbuf.st_mode)){
char *p;
int len;
if ((p = strrchr(dirp->d_name, '.')) != NULL)
if (strcmp(p, ".h") == 0 || strcmp(p, ".c") == 0) {
len = strlen(dir);
if ((filelist[filecount] = (char *)malloc(len + 1)) == NULL){
printf("dynamic memory overflow\n");
return -1;
}
p = filelist[filecount];
strncpy(p, dir, len);
filelist[filecount][len + 1] = '\0';
filecount++;
printf("%d\n",filecount);
}
}
}
}
closedir(dp);
return 0;
}

int main(void){
listfile("/home/shuxiang/nginx/src");
int i;
printf("%d\n",filecount);
for (i = 0; i < filecount; i++){
printf("%s\n",filelist[i]);
free(filelist[i]);
}
return 0;
}
listfile功能是遍历目录并记录所有文件名,src目录下总共有86个.h文件,162个.c文件,当filecount到91时就下不去了。
出现了这个错误:
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. c
[解决办法]

filelist[filecount][len + 1] = '\0';

越界了,应该是
filelist[filecount][len] = '\0';

热点排行