您好我的内存分配问题,
当文本超过1xx个字符时它会终止我不知道最近会发生什么。
的 PS .attention!我的学习和这段代码的质量可能不好
#include <stdio.h>
#include <stdlib.h>
void copy_to_buffer(FILE *fp, int length, char *buffer){
for(int i = 0; i < length; i++){
char c = fgetc(fp);
buffer[i] = c;
}
}
int length_of_text(FILE *fp) {
fseek(fp, 0L, SEEK_END);
int size = ftell(fp);
rewind(fp);
return size;
}
void char_counter(int length, char *buffer, int *charBuffer) {
int counts[128] = { 0 };
for (int i = 0; i < length; i++) {
counts[(int)(buffer[i])]++;
charBuffer[i] = counts[i];
}
for (int i = 0; i < 128; i++) {
charBuffer[i] = counts[i];
if(counts[i] != 0)
printf("%d.(%c) counted: %d times.\n", i,i, counts[i]);
}
}
/***********************************MAIN***********************************/
int main(int argc, char** argv) {
FILE *fp = fopen("tekst.txt" , "r");
int length = length_of_text(fp); //lenght of text
char *buffer = malloc(sizeof(char)*length); //buffer for text from file
if(buffer == NULL)
printf("error");
else
printf("alocated at = %p\n", &buffer);
int charBuffer[128] = {0}; // charcount buffer
buffer[length] = '\0'; // '\0' after last sign
copy_to_buffer(fp, length, buffer);
char_counter(length, buffer, charBuffer);
free(buffer);
fclose(fp);
return 0;
}
答案 0 :(得分:2)
在这一行
charBuffer[i] = counts[i];
当文件大小为&gt; = 128时,您将会溢出charBuffer[128]
,因为i
的索引最多为文件的长度。
答案 1 :(得分:1)
在char_counter
功能中执行
charBuffer[i] = counts[i];
在第一个for循环中但缓冲区仅定义为128个int。如果文本长度超过128个字符,则会导致缓冲区溢出和分段错误。
删除该行并让第二个for循环执行。