Why does this code in c work?

3

When I call the function malloc , I have allocated space only for char , but it works for words of any size, so I was confused.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    char *palavra;
    palavra = malloc(sizeof(char));
    printf("Informe a palavra\n");
    scanf("%s", palavra);
    printf ("%d", conta_vogais(palavra));
}

int conta_vogais (char* s){
    int tamanho = strlen(s);
    char *vogais = {"aeiouAEIOU"};
    int i, j, count = 0;
    for(i = 0; i < tamanho; i++){
        for(j = 0; j < strlen(vogais); j++){
            if(s[i] == vogais[j]){
                count++;
                continue;
            }
        }
    }
    return count;
}
    
asked by anonymous 20.10.2018 / 00:46

1 answer

2

Not wanting to satirize too much, I start by saying this:

You'veseentheresultyouexpected,butthatdoesnotmeanitworks.

ThecodeyouhaverepresentsundefinedbehavioraccordingtotheCmanualforanystringyouenter,sinceyoumustalwaysreserveatleastonemorecaratereforthe%code%terminator.Soit'slikethere'salwaysroomfortheterminator.

Whathappensdependsonmanyfactors,butusuallytakes3forms:

  • Nothingvisiblyhappens.Theoverlappingofmemoryhasnotreplacedanything,andalthoughitsoundslikeluckisactuallybadluckbecauseyoucannotseetheproblem.
  • AccessprotectedmemoryzoneandtheprogramcrasheswithaSegmentationFault.Thisismorenormaltohappenwhentheoverlapistoolarge,asinyourcaseifyouwrite10thousandor100thousandcharacters.Thisisthebestscenarioasyouquicklybecomeawareoftheproblem.
  • Overlaysothervaluesinmemorywithoutcrashing.Thisscenarioisdifficulttodetectandgeneratesallkindsofcrazybehavior,asitendsupchangingothervariablesthathavethesamefunctionwithoutrealizingit.Itispreciselyatthispointthathackerstakeadvantagetodo buffer overflow attacks / in> .
  • 20.10.2018 / 11:12