我遇到问题的函数是我在下面创建的函数DynamicString。 该函数用于创建可变大小的字符串。
.parent
如果有人可以修复我已创建的代码,那将非常有用。我知道可能有更好的算法,但我只是想知道我做错了什么。谢谢!
答案 0 :(得分:1)
首先,正如其他人所指出的那样,正确的字符串结尾为'\0'
,这是一个终止NUL
字符。
其次,如果读取的第一个字符恰好是换行符,则永远不会执行循环。在free(*txt);
*txt
指向tmp
NULL
之后,您无法使用printf("\nThe entered string is : %s",*txt);
,因为您正在取消引用NULL
指针, c。
第三,你有内存泄漏,因为在循环中你使用tmp
将内存分配给malloc()
,每次都会给你一个新的内存地址。这意味着在循环的每个循环中,tmp
将有一个新地址,您将丢失旧地址,并且您无法再释放它。
如果要增加或减少指针指向的内存大小,请使用realloc
。一个非常简单的示例如何使用realloc
就像
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int initalSize = 10;
int increasedSize = 20;
/*
* Because temp type is char, I left sizeof operator out. you can always write like
* char *sentence = malloc(initialSize * sizeof(*sentence)); or
* char *sentence = malloc(initialSize * sizeof(char));
*/
char *sentence = malloc(initalSize);
char *temp = NULL;
/*
* Malloc can return a NULL pointer. You need to check sentence value before using it
* elswhere in the code.
*/
if (!sentence) {
printf("Memory allocation failed for sentence\n");
exit(EXIT_FAILURE);
}
// Some code here...
/*
* Realloc can also return a NULL pointer. Need to use a temporary
* pointer. In case realloc really returns NULL, and you don't use a temporary pointer and
* use it like "sentence = realloc(sentence, increasedSize);", you will have a memory leak
* because now sentence = NULL and you don't have a pointer that points to the old memory.
*
*/
temp = realloc(sentence, increasedSize);
// Also need to check temporary pointer value.
if (!temp) {
printf("Allocating more memory to sentence failed\n");
// One of the possible solutions. You can always use the value that you already have in sentence;
free(sentence);
exit(EXIT_FAILURE);
}
/*
* If everything was ok, you make sentence point to the same address in memory as temp was pointing.
* What it means is that you give ownership of the memory temp points to the sentence.
*/
sentence = temp;
// Some code here...
// No need for sentence anymore
free(sentence);
/*
* It is always recomended to make unused pointers that you don't use anymore or if you have
* freed them to point to NULL;
* It makes sure that those pointers no longer point to the previous memory addresses. Remember that
* free only frees the memory where sentence and temp pointed to.
*
* If you don't make them point to NULL, then sentence and temp would be called a dangling pointer.
*
*/
sentence = NULL;
temp = NULL;
// Some code here...
return 0;
}
如果您使用Linux,最好使用名为Valgrind的程序检查代码。它有助于检测内存泄漏和内存错误。
此外,要阅读stdin
中的字符,我会使用getchar()
。它更简单,更快捷。 Stack Overflow中的一小部分信息回答here。
最后一点,如果你使用的函数不返回任何内容,你就不需要在函数的末尾写return
。