【发布时间】:2018-12-29 20:58:07
【问题描述】:
这是我第一次发布问题,我确实试图找到解决方案,但是,即使我找到了,我也不认识它。
所以,正如标题所说,问题出在这个触发的异常“lab10.exe 中的 0x0F26372D (ucrtbased.dll) 引发的异常:0xC0000005:访问冲突读取位置 0xCCCCCCC4。
如果有针对此异常的处理程序,则程序可以安全地继续。”,当我进入 line -> free(word) 时会发生这种情况。
这在我学习 malloc 时确实发生过几次,但我忽略了它 - 认为还有其他问题。但现在我发现我做错了什么。
程序的重点是 - 编写结构“word”。我需要输入句子并将其“切割”成单词,然后将每个单词与单词中的字母大小和单词的序数一起放入结构中。
#include <stdio.h>
#include <string.h>
struct word {
char text_word[50];
unsigned sizee; //number of letters of the word
unsigned number; //ordinal number of the word
};
void cutting_sentence(struct word *p, char *sen) { //sen is sentence
int size_sen, i, j;
size_sen = strlen(sen) + 1; //size of sentence
p = (struct word*)malloc(size_sen * sizeof(struct word));
if (p == NULL) {
printf("\nNot enaugh memory!");
return 0;
}
strcpy(p[0].text_word, strtok(sen, " ,.!?"));
p[0].sizee = strlen(p[0].text_word);
p[0].number = 1;
printf("word:%s \t size:%u \t ordinal number of the word:%u\n",
p[0].text_word, p[0].sizee, p[0].number);
for (i = p[0].sizee - 1, j = 1;i < size_sen;++i) {
if (*(sen + i) == ' ' || *(sen + i) == '.' || *(sen + i) == ','
|| *(sen + i) == '?' || *(sen + i) == '!') {
strcpy(p[j].text_word, strtok(NULL, " ,.!?"));
p[j].sizee = strlen(p[j].text_word);
p[j].number = j + 1;
printf("word:%s \t size:%u \t ordinal number of the
word:%u\n", p[j].text_word, p[j].sizee, p[j].number);
j++;
}
}
}
int main() {
char sentence[1024];
struct word *word;
printf("Sentence: ");
gets(sentence);
cutting_sentence(&word, sentence);
free(word); //here is exception triggered
return 0;
}
【问题讨论】:
-
您的编译器应该抱怨类型不匹配...在
main函数中,word的类型是什么?那么&word的类型是什么?cutting_sentence的第一个参数的类型是什么?似乎您尝试在 C 中模拟传递引用,但并没有一路走下去。 -
永远不要使用
gets函数! a dangerous function 甚至已从 C 规范中删除。使用例如改为fgets(但请注意它与gets的区别)。 -
words的类型是struct word *。那么&words的类型(作为words的指针)必须是struct word **。不完全是函数所期望的。 -
这是operator precedence的问题。在函数内部,一旦你更正了参数类型,那么表达式
*p[j].sizee实际上等于(*p[j]).sizee。 IE。它试图取消引用p[j]作为指针,但事实并非如此。相反,您需要使用显式括号,例如(*p)[j].sizee。 -
更糟糕的是,
malloc和free首先都没有被正确地拉入命名空间。此代码没有#include <stdlib.h>。如果您将强制转换为malloc(discussed here) 并且代码 pukes 无法编译,那就是您做错了什么的重要线索。
标签: c