【发布时间】:2021-01-30 01:06:13
【问题描述】:
我正在开发一个函数,其中数组的大小从 10 开始,如果 f 的字符串变得更大,他需要分配更多的内存,但是当字符串太大时,我得到一个错误,就像我用 15 输入的东西一样chars 没问题,但是 30 我得到了错误!我不知道为什么。所以希望你能告诉我。
-= 已解决此代码 =-
我的主要:
char *buf;
shellExecute(&buf);
我的代码:
char* shellExecute(char** buf){
int bufSize = 10;
*buf = malloc(bufSize * sizeof(char));
if(*buf == NULL){
printf("[ERROR] can't malloc %d bytes\n", bufSize);
exit(0);
}
char *readpos = *buf;
while (1){
fgets(readpos, bufSize, stdin);
/* Search from the end, as there's where the newline should be */
if (readpos[strlen(readpos)-1] == '\n'){
break;
}
/* Need to allocate more memory */
bufSize += bufSize;
*buf = realloc(*buf, *buf + strlen(*buf) * sizeof(char));
/* Set the pointer to next position to read into */
readpos = *buf + strlen(*buf);
/* Loop takes case of trying again */
}
}
我的错误:
【问题讨论】:
-
使用调试器并单步调试代码......
-
如果你还是
return *buf,传递char**有什么意义? -
@KamilCuk 那不是问题,因为,我已经有一个 void func 并且仍然有错误
-
请不要使用您的固定代码编辑问题和/或答案。它们仅在涉及错误代码时才有意义,并且可以帮助那些自己有类似错误代码的人。如果您想更新解决问题的方法,请发布您自己的答案。
-
@NateEldredge 好的,谢谢