1
Hello, my 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, in the input , the user’s text until the string "the end!" is typed.
However when running the program, I am having the error: Segmentation fault (core dumped). (Detail: This error is common to me, and several times I have tried to solve it, but without success). Please tell us why this error happens, not only in this code but also its common causes.)
Later, I will use the stringUpper function to capitalize my text.
#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)] = '\0'; // 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]);
}
}
Hello, Emoon! I made the necessary modifications. However, with regard to the "Segmentation fault", it continues to appear even if I do a malloc before.
– IPSonic
You could turn the
gdb
to find out exactly what line this Segfault is going on?– Emoon