【发布时间】:2015-04-05 20:36:12
【问题描述】:
下面的 C 代码在我的 mac OS X 环境中运行良好,但如果我尝试在 ubuntu 环境中运行此代码,每当我输入偶数个输入时,我都会遇到 malloc 断言失败,例如“1 2” ,但奇数输入“1 2 3”有效。错误是。
a.out: malloc.c:2372: sysmalloc: 断言 `(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)' 失败。 中止(核心转储)
我不知道 OS X 和 ubuntu 环境之间的区别,所以如果有人能指出问题所在,我将不胜感激。我正在运行 Ubuntu 14.04。它似乎在 y != NULL 循环内崩溃
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
void free_argv(char **argv,int counter)
{
int i = 0;
for(i=0;i<counter;i++)
{
free(argv[i]);
}
free(argv);
}
int main()
{
char *line = NULL;
size_t len = 0;
ssize_t read;
char **argv = NULL;
int counter;
int status;
while ((read = getline(&line, &len, stdin)) != -1)
{
counter = 1;
printf("$ ");
char* x = strtok(line,"\n");
int i = 0;
while(x[i] != '\0')
{
if(x[i] == ' ')
{
counter++;
}
i++;
}
argv = malloc(sizeof(char*)*(counter+1));
argv[counter+1] = NULL;
i = 0;
char* y = strtok(x," ");
printf("user input:\n");
while(y != NULL)
{
argv[i] = malloc(sizeof(char)*strlen(y));
strncpy(argv[i],y,strlen(y));
printf(" %s\n",argv[i]);
y = strtok(NULL," ");
i++;
}
free_argv(argv,counter);
}
return 0;
}
【问题讨论】:
-
argv[i] = malloc(sizeof(char)*strlen(y));没有分配足够的内存,你需要 + 1
-
BTW strdup 会为你做 malloc 和复制
-
@myaut 我不敢相信我错过了 argv[counter+1] = NULL;谢谢!
标签: c