I'm learning C and I'm wondering why the code below didn't crash, I only picked up on the problem using Valgrind.
void push(char *element){
FILE *file = fopen("stack.db", "w");
int rc = fwrite(element, sizeof(element), 1, file);
if (file) fclose(file);
}
void top() {
char *top_element = malloc(sizeof(char));
FILE *file = fopen("stack.db", "r+");
int rc = fread(top_element, sizeof(char), 1, file);
printf("Top element: %s", top_element);
}
int main(int argc, char *argv[]) {
char action = argv[1][0];
switch (action) {
case 'p':
printf("pushing element to stack\n");
push(argv[2]);
break;
case 't':
top();
break;
default:
printf("die\n");
}
return 0;
}
First I call push()
and write argv[2]
to the file. Then I call top()
; I get a piece of memory from malloc, the sizeof char, and assign it to top_element. However, this should be the sizeof char* so I am actually calling malloc(1)
when I should have been calling malloc(8)
. This code works and I only picked up on the error when using Valgrind.
My question is, how does it work when the size of memory that I assigned to top_element
was too small?