MyN*_*ero 4 c malloc pointers realloc
我正在尝试使用malloc和realloc,并针对以下问题提出了一些代码:
我想创建一个未知大小的字符串,不设置任何限制.我可以向用户询问nr个字符,但我更倾向于在用户键入每个字符时调整str的大小.
所以我试图用malloc + realloc做这个,并且想法是每次用户输入一个新的char时,我使用realloc请求+1内存来保存char.
在尝试实现这一点时,我犯了一个错误,最后做了以下事情:
int main () {
/* this simulates the source of the chars... */
/* in reality I would do getch or getchar in the while loop below... */
char source[10];
int i, j;
for (i=0, j=65; i<10; i++, j++) {
source[i] = j;
}
/* relevant code starts here */
char *str = malloc(2 * sizeof(char)); /* space for 1 char + '\0' */
int current_size = 1;
i = 0;
while(i<10) {
char temp = source[i];
str[current_size-1] = temp;
str[current_size] = '\0';
current_size++;
printf("new str = '%s' | len = %d\n", str, strlen(str));
i++;
}
printf("\nstr final = %s\n", str);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意,realloc部分尚未实现.
我编译并执行了这段代码并获得了以下输出
new str = 'A' | len = 1
new str = 'AB' | len = 2
new str = 'ABC' | len = 3
new str = 'ABCD' | len = 4
new str = 'ABCDE' | len = 5
new str = 'ABCDEF' | len = 6
new str = 'ABCDEFG' | len = 7
new str = 'ABCDEFGH' | len = 8
new str = 'ABCDEFGHI' | len = 9
new str = 'ABCDEFGHIJ' | len = 10
Run Code Online (Sandbox Code Playgroud)
我发现这些结果很奇怪,因为我期望程序崩溃:str有2个字符的空间,并且代码向str添加超过2个字符而不需要更多内存.根据我的理解,这意味着我正在写入我不拥有的内存,因此它应该给出运行时错误.
所以...为什么这样做?
(编译器是GCC 4.3.4.)
提前致谢.
编辑: 其中一位评论者建议调用free()可能会导致错误信号.我尝试使用上面的代码调用free(),并且没有因执行代码而导致错误.但是,在向源数组添加更多项目并且还调用free之后,获得了以下错误:
*检测到glibc ./prog:free():下一个大小无效(快):0x09d67008**