Hello, friends!
I am creating a program that will read a text. This text should be allocated one line at a time (up to 75 characters per line).
The program receives, at the input, the user's text until the string "the end!" is typed.
However when I run the program, I'm getting the error: Segmentation fault (core dumped). (Detail: This error is common to me, and for several times I have tried to solve it, but without success). Please tell why this error happens, not only in this code but also its common causes.)
Later, I'll use the stringUpper function to leave my text in uppercase.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX_CHAR 75
const char THE_END[] = "the end!";
void stringUpper(char*, int);
void main() {
char **texto;
int i = 0;
int j;
texto = NULL;
for( ; ; ) {
texto = (char**)realloc(texto,(i+1)*sizeof(char*));
texto[i] = (char*)malloc(MAX_CHAR*sizeof(char));
fgets(texto[i],MAX_CHAR,stdin);
texto[strlen(texto[i]-1)] = '#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX_CHAR 75
const char THE_END[] = "the end!";
void stringUpper(char*, int);
void main() {
char **texto;
int i = 0;
int j;
texto = NULL;
for( ; ; ) {
texto = (char**)realloc(texto,(i+1)*sizeof(char*));
texto[i] = (char*)malloc(MAX_CHAR*sizeof(char));
fgets(texto[i],MAX_CHAR,stdin);
texto[strlen(texto[i]-1)] = '%pre%'; // troca o '\n' (úlimo dígito da string) pelo terminador nulo
if(strcmp(THE_END,texto[i]) == 0) break;
i++;
}
for(j = 0; j < i; i++) {
free(texto[j]);
}
free(texto);
}
void stringUpper(char *s, int tam) {
int i = 0;
for(i = 0; i < tam; i++) {
s[i] = toupper(s[i]);
}
}
'; // troca o '\n' (úlimo dígito da string) pelo terminador nulo
if(strcmp(THE_END,texto[i]) == 0) break;
i++;
}
for(j = 0; j < i; i++) {
free(texto[j]);
}
free(texto);
}
void stringUpper(char *s, int tam) {
int i = 0;
for(i = 0; i < tam; i++) {
s[i] = toupper(s[i]);
}
}