C: pointers libraries structs Flashcards
what is static lifetime vs auto lifetime?
Variables declared outside of a function have storage class static. Lifetime begins when a program is loaded, ends when program ens.
Variables declared inside of a function by default have storage class auto. Dies when function call returns.
Variables declared inside of a function may be explicitly declared static. Such variables have local scope, but the global lifetime of static variables.
Where in the structure of a program do auto variables live? Can you trust the values of initialized variables here?
The stack. Values of uninitialized variables are random.
What data goes into the heap?
Long term malloc()’d data
Where do uninitialized static variables live? Can you trust the values stored here by default?
BSS. Always initialized to 0.
Where do initalized static variables live?
.data
are C functions call by value or address?
value. bypass w/ pointers
$ a.out 1 23 “four five”
what is argc, argv?
argc: 4 (includes program name)
argv: [1, 23, “four five”]
Is this legal?
char *makeBig(char *s) {
s[0] = toupper(s[0]);
return s;
}
…
makeBig(“a cat”);
…
No. this code will likely fail because compilers typically place literal strings in a read-only area of the address space
Why is strncpy safer than strcpy?
char *strncpy(char *dest, char *source, int num)
stops copying after num chars, and appends a /0
less likely to go beyond bounds
is there a better way to declare this struct to save memory?
struct {
char x;
int y;
char z;
} s1;
Yes. If the chars are placed next to each other in memory, there probably wont be as much padding around the chars for alignment.
typedef struct {
unsigned int version:2;
unsigned int p:1;
unsigned int cc:4;
unsigned int m:1;
unsigned int pt:7;
u_int16 seq;
u_int32 ts;
} rtp_hdr_t;
What is this an example of?
Bit fields. version, for example, is declared to be 2 bits long, and will only take up 1 byte of memory.
union u_tag {
int ival;
float fval;
char *sval;
} u;
what is sizeof(u)? in terms of its attributes.
sizeof(float)
where does getchar() read from?
stdin
what is a buffer?
“buffer” typically refers to a memory area used for temporary storage. To declare a buffer, you can use an array. For example:
char buffer[256];
In C, the fflush
function is used to flush (clear) the output buffer. It ensures that any data that was buffered for output is actually written to the file or console. Here’s a concise example:
```c
fflush(stdout); // Flushes the standard output buffer.
~~~
This is particularly useful when you want to make sure that data is immediately written to a file or displayed on the screen instead of being held in a buffer.
the fflush
function is used to flush (clear) the output buffer. It ensures that any data that was buffered for output is actually written to the file or console. Here’s a concise example:
fflush(stdout); // Flushes the standard output buffer.
Essentially, “save” progress, and get ready for whats next.