Why does this c code work?

Asked

Viewed 156 times

3

When I call the call malloc, I only had space for one char, but it works for words of any size, so I got 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;
}
  • When you allocate, it reserves the amount in the String type memory, and if you only enter one word it will work, now if you put space and enter the second word it will not work. Check this link out: * Source: https://www.ime.usp.br/~elo/Introducaocomputacao/Caracter.htm

1 answer

2

Not to oversimplify, I start by saying this:

inserir a descrição da imagem aqui

You saw the result you expected, but that doesn’t mean it works.

The code you have represents undefined behavior according to the C manual for any string that is entered, as you must always reserve at least one more character for the terminator \0. So it’s like there’s only room for the terminator.

What happens will depend on numerous factors, but usually takes 3 forms:

  1. Nothing visibly happens at all. The memory overlap has not replaced anything, and although it seems lucky it is actually unlucky because you can not perceive the problem.
  2. Access protected memory zone and program crashes with a Segmentation Fault. This is more normal to happen when the overlap is too large, as in your case if you write 10,000 or 100,000 characters. This is the best scenario because you quickly realize the problem.
  3. It overrides other values in memory without blowing up. This scenario is difficult to detect and generates all kinds of crazy behaviors, as it ends up changing other variables that have the same function without being aware. It is precisely at this point that hackers take advantage to do attacks of buffer overflow.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.