im having a problem in my code, when i run it i got a segmentation fault in malloc() function. here's my code, im new here so sorry if i write something wrong.
Sorry my bad english !
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef char String[50];
bool equalsIgnoreCase(char*,char*);
void main(){
String nome;
printf("Digite um nome: "); //name
scanf("%s",nome);
if(equalsIgnoreCase(nome,"TESTE")){ //test
printf("Strings iguais.");
}else printf("Strings diferentes.");
}
bool equalsIgnoreCase(char *str1 , char *str2){
char *a,*b;
a = malloc(sizeof(char)); //segmentation fault here
b = malloc(sizeof(char));
for(;str1 != '\0';str1++,str2++){
a = tolower(str1);
b = tolower(str2);
if(strcmp(a,b)!=0){
free(a);
free(b);
return false;
}
}
free(a);
free(b);
return true;
}
mallocis called?a = malloc(sizeof(char))is allocating 1 byte of memory? You cannot use that to store a string (the terminating null byte will consume the one byte that's available). If you only want one byte, just declare it. You are also mixing up pointers vs. what they point to rather severely.a = tolower(str1);..if(strcmp(a,b)!=0){is wrong.