我有一个程序,用户输入他们想要的句子数,然后提示输入句子。他们不能输入十多个句子。当我测试,如果我输入超过5,我得到一个总线错误代码。这是我的代码,我在.h文件中调用两个函数,我不相信是相关的,但无论如何我会提供它们。
//this program will take in user input for a number of sentences up to ten, each with 100 char or less, and convert them all to uppercase
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "convert.h"
int main () {
int i; //increment
int numberofsentences; //number of sentences
char **sentence_array; // sentence array
sentence_array = (char **)malloc(numberofsentences*sizeof(char));
printf ("I will take up to ten sentences of up to 100 chars each, and convert them to uppercase, as well as give you stats on them. \n");
printf ("How many sentences would you like? \n");
scanf ("%d", &numberofsentences);
fgetc(stdin);
//user inputs the sentences based on the number that was provided
for (i = 0; i< numberofsentences; i++) {
sentence_array[i] = (char *)malloc(100 * sizeof(char));
printf ("Enter sentence :");
fgets(sentence_array[i], 101, stdin);
printf ("\n");
}
//call function that converts all arrays to uppercase
convertAll(sentence_array, numberofsentences);
printf("Your converted sentences are: \n");
//print out every sentence thats converted to uppercase
for (i = 0; i < numberofsentences; i++){
//convertSentence(sentence_array[i]);
printf("%s", sentence_array[i]);
}
}
和functions.c文件
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include "convert.h"
//function to convert char array to uppercase
void convertSentence(char *sentence){
int i;
for (i = 0; i <strlen(sentence); i++){
sentence[i] = toupper(sentence[i]);
}
}
//function to convert array of all sentences and converts all to upper
void convertAll(char **sentenceList, int numOfSentences){
int i;
for (i = 0; i < numOfSentences; i++){
convertSentence(sentenceList[i]);
}
}
我觉得它与内存分配有关。 并且作为一个注释:我知道scanf和fgets很糟糕,但是我的教授告诉我们使用它们......感谢您的帮助
答案 0 :(得分:1)
这是预期的,因为
sentence_array = (char **)malloc(numberofsentences*sizeof(char));
没有为numberofsentences
指针分配足够的内存。因此,在存储了几个句子后,您会遇到内存违规或任何其他UB。
sizeof
错了,应该是:
sentence_array = malloc(numberofsentences*sizeof(char *));
除此之外:不需要演员:Do I cast the result of malloc?(答案是否,BTW)
编辑:我的答案不完整,H.S。指出问题的另一部分(未初始化的值),可以通过以下方式轻松避免:(加上另一个fgets
边界错误)
这将教会我尝试手动修改OP代码。
答案 1 :(得分:1)
在此声明中:
sentence_array = (char **)malloc(numberofsentences*sizeof(char));
在初始化之前使用局部变量numberofsentences
,这是一种未定义的行为。此外,sentence_array
应该分配char
指针数组的内存,即numberofsentences*sizeof(char *)
,并将此语句移到numberofsentences
输入语句下方。
所以,它应该是这样的:
scanf ("%d", &numberofsentences);
fgetc(stdin);
sentence_array = malloc(numberofsentences*sizeof(char *));
[您不需要投出malloc
结果]
此外,这里
fgets(sentence_array[i], 101, stdin);
^^^
可能发生缓冲区溢出。 sentence_array[i]
已分配内存以容纳100
个字符,并且您将101
作为要复制到sentence_array[i]
的最大字符数。 fgets()
从流中读取字符并将其存储到缓冲区(此处为sentence_array[i]
),直到(num-1)
(此处为101-1
)个字符已被读取或者是换行符或到达文件的末尾,以先发生者为准,在复制到缓冲区的字符后,自动附加终止空字符。因此,它可能导致缓冲区溢出。它应该是:
fgets(sentence_array[i], 100, stdin);