[英]Program crashing when a function is used many times
I need to use the algorithm of linked list in my program. 我需要在程序中使用链表算法。 I will explain quickly what it need to do:
我将快速解释它需要做什么:
My program generate a string with maximum size 2.000. 我的程序生成的字符串最大大小为2.000。 I need to create a linked list of elements of the following type:
我需要创建以下类型的元素的链表:
typedef struct List * News;
struct List {
char * Text;
News next;
} ;
Since the maximum size of the struct is 2.000, to put the information of one struct it my text field, I want to use the exact size of the struct. 由于该结构的最大大小为2.000,因此要将一个结构的信息放入文本字段中,我想使用该结构的确切大小。 So, I made the following function to create and add an element on the top of my linked list:
因此,我做了以下函数来在链接列表的顶部创建并添加一个元素:
void InsertLL (News p, char M[]){
char * text = (char *)malloc(strlen(M) * sizeof(char));
strcpy(text, M);
News s,t;
t = malloc(sizeof(struct List));
t-> Text = text;
s=p;
p=t;
t -> next = s;
}
The program run in a infinite loop, and after a while running, it crashes. 程序以无限循环运行,一段时间后运行会崩溃。 Without the function InsertLL, it runs well (for example, if I don't care for the size of my struct and put it directly on my element).
没有功能InsertLL,它运行良好(例如,如果我不在乎结构的大小,直接将其放在元素上)。 On debug mode, it doesn't crash, so I think it is some kind of memory problem that I couldn't solve yet.
在调试模式下,它不会崩溃,因此我认为这是我尚无法解决的某种内存问题。
is there something I am doing wrong when I call malloc? 调用malloc时我做错了什么吗?
Thanks for your help! 谢谢你的帮助!
You are not allocating enough space for text. 您没有为文本分配足够的空间。 You should consider space of null character as well so allocate strlen(M)+1 bytes.
您还应该考虑空字符的空间,因此分配strlen(M)+1个字节。
sizeof(char)
is always one byte and you need not to typecast the malloc result as void * is automatically and safely promoted to any other pointer type. sizeof(char)
始终为一个字节,您无需强制转换malloc结果,因为void *将自动安全地提升为任何其他指针类型。
Change the code to char * text = malloc(strlen(M)+1);
将代码更改为
char * text = malloc(strlen(M)+1);
You are not allocating space for the null terminator. 您没有为空终止符分配空间。 Pass strlen()+1 to malloc when allocating strings.
分配字符串时,将strlen()+ 1传递给malloc。 Remember that strlen() returns the length of the string excluding the null terminating character.
请记住,strlen()返回字符串的长度, 不包括空终止符。
Note that sizeof(char) is 1 by definition, and that you should not cast the return value of malloc . 请注意,根据定义,sizeof(char)为1,并且您不应该转换malloc的返回值 。 Your code should be
您的代码应为
char * text = malloc(strlen(M) + 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.