1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#define log_str(n) printf("%s == \"%s\"\n", #n, (n))
#define log_addr(n) printf("%s == %p\n", #n, (void*)(n))
int main(int argc, char* argv[]) {
char stack_str[] = "ABC";
log_str(stack_str);
log_addr(stack_str);
char* data_str = "ABC";
log_str(data_str);
log_addr(data_str);
char* heap_str = malloc(sizeof(*heap_str) * 4);
// pitfall: this is not assigning "ABC" into the recently malloced heap_str
// this is overwriting the address, so we lost what we malloced
//heap_str = "ABC";
// correct way to fill a heap allocated array
heap_str[0] = 'A';
heap_str[1] = 'B';
heap_str[2] = 'C';
heap_str[3] = '\0';
log_str(heap_str);
log_addr(heap_str);
//free(heap_str);
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2024 Alexander J. Quinn & David Burnett This content is protected and may not be shared, uploaded, or distributed.