我已经阅读了另一个关于使用 realloc 获取指向更大内存地址空间开头的新指针的 SO question,但我无法弄清楚我做错了什么。它打印回溯和内存转储。后来我尝试访问 strhldr 但我认为它甚至没有那么远。
char *strhldr = (char *)malloc(strsize);
int chrctr = 0;
if(chrctr == strsize - 3){ // when you get close
strsize = strsize*2; //double size
char *temp = realloc(strhldr, strsize); //make more room
if(temp == NULL)
printf("reallocate failed\n");
else{
strhldr = temp;
free(temp); // removed same issue
}
}
// Later attempt to add it to an array
cmdargs[i] = strhldr;
这都在一个 while 循环中,其中 chrctr 和 strsize 递增
完整代码
int argctr = 64;
char **cmdargs = (char **) malloc(argctr * sizeof(char*));
char c = getchar();
int i = 0;
while(c != '\n' && c != EOF){ //read through a String of stdin
int strsize = 32;
char *strhldr = (char *)malloc(strsize);
char *strstarthldr = strhldr;
if(c == ' ')
c = getchar();
while(c != ' ' && c != '\n' && c != EOF){
int chrctr = 0;
if(chrctr == strsize - 3){ // when you get close
strsize = strsize*2; //double size
char *temp = realloc(strhldr, strsize); //make more room
if(temp == NULL)
printf("reallocate failed\n");
else
strhldr = temp;
} //add that word to the array of strings
strhldr[chrctr] = c;
chrctr++;
c = getchar();
}
strhldr[charctr] = '\0';
//strhldr = strstarthldr;
cmdargs[i] = strhldr;
i++;
}