Memory allocation for string array with malloc()

Asked

Viewed 102 times

2

This code below asks for a num for the amount of strings I want to store in vetor which in this case is the pointer char *strings[num].

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

int main()
{
    int num = 0;
    char *strings[num];
    void string_alunos(char *strings[], int num);

    printf("Quantas strings voce deseja armazenar? ");
    scanf("%d", &num);
    printf("\n");

    printf("Digite as palavras:\n");
    for (int i = 0; i < num; i++)
    {
        strings[i] = (char *)malloc(sizeof(char) * 30);
        if (strings[i] != NULL)
        {
            fflush(stdin);
            scanf("%30[^\n]", strings[i]);
        }
        else
        {
            printf("*** Não foi possível alocar memoria! ***");
            exit(1);
        }
    }
    string_alunos(strings, num);
    free(strings);

    return 0;
}
void string_alunos(char *strings[], int num)
{
    printf("\n::: PALAVRAS :::\n");
    for (int i = 0; i < num; i++)
    {
        printf("%s\n", strings[i]);
    }
}

When using the malloc() i want a maximum string of 30 characters. With malloc() in theory it should reserve 30 bytes in memory. right? Or not? Anyway, I circled the debug mode, and the positions between strings give a total of 56 bytes of difference between one and the other, why does this happen? There should be a difference of 30 bytes?

Imagem do debug mode adicionado os endereços de memória

1 answer

3


The main problem is that you are initiating the array 0 then will only corrupt the memory by putting things where nothing has been reserved. Sending it to boot after you know how big it should be.

There is a problem that is not serious in such an exercise, but since it was to make the release then release something correct. strings was never allocated with malloc() so there’s no point in giving free() but all elements of it were initialized with malloc() then it must give free() in all. I would not even have created the function to write on the screen, because then had to make 2 loops without need.

Still had an error in data entry formatter which I fixed.

And I’ve added an extra character to the terminator of string, otherwise would give problem in some cases.

I took some things that do not make sense or it is innocuous or even wrong to do. You must have learned to do so in bad sources.

I didn’t optimize to avoid the malloc(). Since the size of string is known could allocate everything in the same stack (although it would be good to validate the maximum), since it started doing this, and avoid the malloc() which would simplify the code, but I’m not sure what the goal is. Anyway it would make more sense everything in automatic memory or everything in dynamic memory.

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

void string_alunos(char *strings[], int num) {
    printf("\n::: PALAVRAS :::\n");
    for (int i = 0; i < num; i++) printf("%s\n", strings[i]);
}

int main() {
    int num;
    printf("Quantas strings voce deseja armazenar? ");
    scanf("%d", &num);
    char *strings[num];
    printf("\n");
    printf("Digite as palavras:\n");
    for (int i = 0; i < num; i++) {
        strings[i] = malloc(31);
        if (strings[i] != NULL) scanf("%30s[^\n]", strings[i]);
        else {
            printf("*** Não foi possível alocar memoria! ***");
            exit(1);
        }
    }
    string_alunos(strings, num);
    for (int i = 0; i < num; i++) free(strings[i]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • The code has some unnecessary things, like the function, for example, because the teacher asked in the exercise in this way. Anyway, just a doubt, you commented that there was an error in the input formatter, would it be because I didn’t put that’s next to %30? If yes, what would that’s'? Besides, you ended up removing that fflush(stdin), if I remove this, the execution jumps straight to the end of the qnd program I inform the number of strings, wouldn’t that be to clear the keyboard buffer? Thanks for the help!

  • 1

    The s says you should take a string, without it is not saying what to take, has implementation that can work by coincidence. In C almost everything can work by coincidence, but it must always work. It is the case of fflush(), only works in certain implementations, not at all, so you should not use. https://answall.com/q/325628/101 e https://answall.com/a/453303/101 e

  • Oops, sorry to be back here again.. but I was testing what you had commented about putting the type of data that I would read in the scanf "scanf("%30s[ n]", strings[i])" in the case here would be the string’s', however, by putting this at the time of returning the string it returns only what is before the space " ", if I type for example, basketball, returns only ball, if I withdraw this’s' it returns the whole string, would you know a way to solve? and to clear the keyboard buffer agr I’m using the while ((c = getchar()) != ' n' && c != EOF){}

  • See the links I went through, there’s a lot of information about it, including how ineffective it is to read sentences with scanf().

  • Yeah, I took a look and saw that to read the data, at least in simple exercises so the ideal is fgets(), but I’m not able to use it in the program.. What would be the right way to use based on this program I did? this way here: fgets(strings[i], 31, stdin) she reads straight, type if qro store 3 strings, I type 'pedro' 'Joao' 'Gustavo', in output comes out 'pedro' 'Ustavo he is always skipping a line, would know how to solve this?

  • 1

    https://answall.com/a/216450/101

Show 1 more comment

Browser other questions tagged

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