0
I wrote this simple program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *nome;
nome = (char *)malloc(10 * sizeof(char));
if(nome == NULL) {
puts("Erro de alocacao!");
exit(1);
}
scanf(" %s", nome);
nome = (char *)realloc(nome, strlen(nome));
if(nome == NULL) {
puts("Erro de realocacao!");
exit(2);
}
printf("%s\n", nome);
free(nome);
return 0;
}
Apparently you don’t have any mistakes, do you? But the truth is, depending on mine input, an execution error occurs called:
corrupted size vs. prev_size Aborted (dumped core)
I just did the tests here and sizeof(char) returns 1, ie 1 byte and not 4 bytes.
– Patrick Cardoso
I’m using gcc, not g++.
– Patrick Cardoso
The above comments are completely mistaken. The specification of C and C++ is clear that the type size
char
is always 1 so it makes no sense to usesizeof(char)
, just as it is bad, and even wrong to do cast inmalloc()
.gcc
andg++
are not the same compiler.– Maniero
Yes I also found strange the answers of the friend, I have read in several places about gcc and g++, and no one talked about the two being the same thing. Speaking of malloc(), I’ve also read several codes where casting is done, but when I don’t do the compiler doesn’t issue any Warning, so I think without casting is also correct.
– Patrick Cardoso
It is correct without the casting, Working is different than being right, which is why I said that’s not how you learn, you’ll learn a lot of wrong things just because it works. In certain languages this may not even be such a big problem, in C believing that working is the same as being right is a huge problem, so I reaffirm that I can not learn on the basis of trial and error.
– Maniero
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site
– Maniero