CSE 101

CSE 101 · WEEK 09 · READING

Computer networks, pointers and strings

How messages reach other computers—and how C programs refer to objects and bounded text in memory.

The network discussion and C memory examples are two complementary strands. Read the diagrams, predict the traces and open each Check answer afterward. Lab 8 uses bounded text with supplied communication support; implementing a network stack is not required. The final signaling illustrations are optional references. Click a figure to enlarge it; wide tables and code scroll sideways.

1. Communication needs representation and a recipient

Sending a message requires more than moving energy or an object. A sender must represent information, a carrier must convey it, and a recipient must interpret it. The parties need enough shared conventions to distinguish a meaningful message from an unexplained signal. A network adds the challenge of selecting among many possible recipients using shared infrastructure.

Historical communication illustrations from the instructor’s source. They suggest different carriers; the pigeon photograph is not evidence of an ordinary message-delivery arrangement.
Figure 1. Historical communication illustrations from the instructor’s source. They suggest different carriers; the pigeon photograph is not evidence of an ordinary message-delivery arrangement. CSE101 Week 9, slide 3. Source slide.
A telegraph mechanism and Morse alphabet. Agreed signal patterns let a receiver reconstruct characters.
Figure 2. A telegraph mechanism and Morse alphabet. Agreed signal patterns let a receiver reconstruct characters. CSE101 Week 9, slide 4. Source slide.

A telegraph illustrates the separation between a physical signal and a code. A circuit can carry electrical changes without knowing the meaning of a sentence. Meaning comes from conventions used at its ends. Automating the encoding and decoding lets a person work with keys and printed characters rather than producing every signal by hand.

The Hughes printing telegraph and a separate teleprinter code chart. These are related historical developments, not proof that the Hughes mechanism used the pictured code.
Figure 3. The Hughes printing telegraph and a separate teleprinter code chart. These are related historical developments, not proof that the Hughes mechanism used the pictured code. CSE101 Week 9, slide 5. Source slide.
Teleprinters turn typed characters into signals and received signals back into readable output.
Figure 4. Teleprinters turn typed characters into signals and received signals back into readable output. CSE101 Week 9, slide 6. Source slide.
Check: If two terminals use the same wire but interpret the signal patterns differently, is the physical connection enough?

No. They also need compatible encoding and communication rules. Receiving a signal does not establish that its information has been understood.

2. Switching makes shared infrastructure possible

A telex terminal: a switched service selects the distant terminal instead of requiring a dedicated direct wire to every recipient.
Figure 5. A telex terminal: a switched service selects the distant terminal instead of requiring a dedicated direct wire to every recipient. CSE101 Week 9, slide 7. Source slide.

If every pair of n devices needs its own direct connection, there are n(n − 1)/2 pairs. Ten devices already require 45 pairwise links. Switching allows devices to share a network of intermediate connections. The network selects a path or a forwarding action rather than installing a separate end-to-end wire for every pair.

Circuit switching establishes a path through switching offices. Resources are reserved for the connection’s duration.
Figure 6. Circuit switching establishes a path through switching offices. Resources are reserved for the connection’s duration. CSE101 Week 9, slide 8. Source slide.
Original photographs of physical switching equipment. Selected inputs and outputs can be connected by switching mechanisms.
Figure 7. Original photographs of physical switching equipment. Selected inputs and outputs can be connected by switching mechanisms. CSE101 Week 9, slide 9. Source slide.

In circuit switching, setup reserves resources along a path. Reserved capacity can remain unused during a quiet period, but it is available to that connection. If suitable resources are unavailable, a new connection may be refused. A circuit is a service arrangement; it need not mean one uninterrupted dedicated copper wire from sender to receiver.

Check: Why can a reserved circuit waste capacity when a user pauses between short messages?

The reserved resources remain committed even while that user sends nothing. Other traffic cannot automatically use that reserved portion during the pause.

3. Packet switching shares link time

Packets carry headers and payloads through shared links. The pictured alternatives are possible paths, not a requirement that every packet take a different route.
Figure 8. Packets carry headers and payloads through shared links. The pictured alternatives are possible paths, not a requirement that every packet take a different route. CSE101 Week 9, slide 10. Source slide.

A packet groups a payload with control information such as addressing. Packet switching lets transmissions from different conversations share a link over time. An intermediate device receives a packet, makes a forwarding decision and sends it onward. In a store-and-forward model, receipt precedes onward transmission. The exact behavior depends on the technology.

The postal sorting analogy: receive an item, inspect delivery information and forward toward another stop. The original photographic credits are retained.
Figure 9. The postal sorting analogy: receive an item, inspect delivery information and forward toward another stop. The original photographic credits are retained. CSE101 Week 9, slide 11. Source slide.
Final delivery differs from intermediate sorting. An application interprets the message after network delivery has done its part.
Figure 10. Final delivery differs from intermediate sorting. An application interprets the message after network delivery has done its part. CSE101 Week 9, slide 12. Source slide.

Sharing is useful for bursty traffic, but it introduces contention. Packets can wait in queues, and a full queue can cause drops. Paths and delays can differ; arrival order need not match sending order. A packet network therefore does not by itself promise timely, ordered or successful delivery of every message.

Comparing the service models
QuestionCircuit switchingPacket switching
Before sendingEstablish a circuitUse packet headers and forwarding rules
Quiet intervalReserved capacity may sit idleOther traffic can use link time
Heavy demandA new circuit can be refusedQueues and losses can increase
Check: Does packet switching eliminate waiting because there is no permanently reserved circuit?

No. Multiple senders can compete for the same outgoing link. Queueing delays and drops remain possible.

4. A transfer rate is not an arrival time

In this discussion, bandwidth refers to a link’s data-transfer rate, measured in bits per second. Latency is a delay. Throughput is the rate actually achieved over an interval. A high nominal rate does not guarantee low latency or an equally high application throughput.

A 1,000-byte packet contains 8,000 bits in this illustrative calculation. On a 1 Mbit/s link, placing those bits on the link takes 8,000 / 1,000,000 = 0.008 seconds, or 8 ms. This transmission delay is different from propagation time through the medium, processing time and time spent queued. Protocol overhead would add transmitted bits beyond an application payload.

Illustrative one-link delay budget
ContributionAssumed delay
Transmit 1,000 bytes at 1 Mbit/s8 ms
Propagation10 ms
Processing1 ms
Queueing5 ms
Total under these assumptions24 ms

Increasing the link rate to 10 Mbit/s reduces transmission to 0.8 ms, giving 16.8 ms if the other assumed delays remain unchanged. It does not reduce the total tenfold. Multiple links introduce additional contributions; this small budget is not a measurement or a complete Internet timing model.

Check: A faster link reduces transmission time. Why might a user still wait a long time for a response?

Propagation, queueing, server work and other stages can dominate. Measure the whole request path and identify which part is actually slow.

5. Scope and topology describe different properties

People use services provided by connected devices. A network includes endpoints, links and rules, not only a drawing of social relationships.
Figure 11. People use services provided by connected devices. A network includes endpoints, links and rules, not only a drawing of social relationships. CSE101 Week 9, slide 15. Source slide.

PAN describes a personal-area network, LAN local connectivity, and WAN wide-area connectivity between distant sites. These labels describe scope, not a guaranteed speed, owner or physical shape. A campus can contain many network segments, and devices within one building can use different services and technologies.

A bus topology uses a shared medium. Access rules and faults affect the devices sharing it.
Figure 12. A bus topology uses a shared medium. Access rules and faults affect the devices sharing it. CSE101 Week 9, slide 17. Source slide.
A star topology connects links to a central device. The original center is labelled Computer; a modern Ethernet LAN commonly uses a switch in that position.
Figure 13. A star topology connects links to a central device. The original center is labelled Computer; a modern Ethernet LAN commonly uses a switch in that position. CSE101 Week 9, slide 18. Source slide.

A topology describes the arrangement of connections. A star with a hub and a star with a switch have similar drawings but different internal behavior. Shape alone does not identify forwarding rules. It also affects failure consequences: a broken edge link and a failed central device need not affect the same number of endpoints.

Check: Does the label LAN tell you that all its traffic uses one shared bus?

No. Scope and topology are separate properties. A LAN can use switched links, wireless access or a combination.

6. Sharing and direction require rules

The shared-medium Ethernet illustration is historical. Collision detection belongs to shared half-duplex Ethernet, not full-duplex switched links.
Figure 14. The shared-medium Ethernet illustration is historical. Collision detection belongs to shared half-duplex Ethernet, not full-duplex switched links. CSE101 Week 9, slide 19. Source slide.

When devices share a medium, simultaneous transmissions can interfere. Classic half-duplex Ethernet used carrier sensing and collision detection, CSMA/CD. Full-duplex Ethernet links do not use CSMA/CD. Wi-Fi commonly coordinates access to shared airtime using collision-avoidance mechanisms. Do not apply a historical bus rule indiscriminately to every connection called a network.

Simplex, half-duplex and full-duplex describe permitted directions of communication. The device drawings illustrate the directions rather than all features of those devices.
Figure 15. Simplex, half-duplex and full-duplex describe permitted directions of communication. The device drawings illustrate the directions rather than all features of those devices. CSE101 Week 9, slide 20. Source slide.

Simplex is one-way communication. Half-duplex allows both directions but at different times. Full-duplex allows simultaneous communication in both directions. These describe direction, not whether an application delivers reliable messages or reserves an end-to-end circuit.

Check: Does full duplex mean that every packet must arrive successfully?

No. It describes simultaneous two-way communication. Delivery guarantees and recovery are separate properties.

7. A switch and a router do different work

Historical local-network connections. A repeater regenerates signals; a bridge or switch makes frame-forwarding decisions. The combined label does not make these devices equivalent.
Figure 16. Historical local-network connections. A repeater regenerates signals; a bridge or switch makes frame-forwarding decisions. The combined label does not make these devices equivalent. CSE101 Week 9, slide 21. Source slide.
IP routers connect networks using different local-link technologies. A packet can cross both wired and wireless segments.
Figure 17. IP routers connect networks using different local-link technologies. A packet can cross both wired and wireless segments. CSE101 Week 9, slide 22. Source slide.
Roles that can coexist in one physical box
FunctionMain responsibility
RepeaterRegenerate or relay physical signals.
Ethernet switchForward link-layer frames using MAC information and a forwarding table.
Access pointConnect wireless devices to a LAN through link-layer communication.
IP routerSelect an outgoing path for packets between IP networks using destination IP information.

A home device called a router often combines an IP router, Ethernet switch and wireless access point. Recognizing the separate roles helps explain a failure. A device might maintain local Wi-Fi connectivity while its upstream Internet path is unavailable. A successful connection to the local access point does not prove reachability of every remote server.

Check: Two devices can communicate locally, but a remote service is unreachable. Does this prove the wireless link has failed?

No. Local communication is evidence that part of the path works. The upstream route, remote service or another dependency may be responsible.

8. Addresses and forwarding decisions have a scope

An IP address identifies an interface or a set of interfaces at the network layer; a device can have several. IPv4 uses 32-bit addresses and IPv6 uses 128-bit addresses. A MAC address is used in local-link delivery. A transport port helps distinguish service endpoints. Human-readable names and DNS are developed in Week 10. These identifiers answer different questions.

Illustrative forwarding table at router R
Destination networkR’s action
ADeliver on the attached A link
BForward to router S
CForward to router T
OtherUse a configured default route, or handle absence of a route

For a packet addressed to network C, R forwards toward T. R does not need to store a complete route description for that individual journey. The next router makes its own forwarding decision. A forwarding table is used to choose an outgoing link or next hop; mechanisms that build and update such tables are a separate topic.

In ordinary forwarding without address translation, the final destination IP remains the destination, while link-layer delivery addresses change for the next link. Routers also update fields such as hop limits as required. An “intermediate address” in a schematic should not be read as a claim that each router replaces the packet’s destination IP with its own address.

Check: In the example, is T necessarily the final recipient of the application’s message?

No. T is the next router toward network C. A next-hop delivery target and the final endpoint are different roles.

9. One receiver, a local audience or a group

Unicast addresses one receiving endpoint. The drawn line is conceptual delivery, not a dedicated physical wire.
Figure 18. Unicast addresses one receiving endpoint. The drawn line is conceptual delivery, not a dedicated physical wire. CSE101 Week 9, slide 26. Source slide.
Original local and directed-broadcast illustrations. Broadcast scope is constrained; these arrows do not authorize forwarding broadcasts across arbitrary networks.
Figure 19. Original local and directed-broadcast illustrations. Broadcast scope is constrained; these arrows do not authorize forwarding broadcasts across arbitrary networks. CSE101 Week 9, slide 27. Source slide.
Multicast addresses a group of interested receivers rather than every node shown in the network.
Figure 20. Multicast addresses a group of interested receivers rather than every node shown in the network. CSE101 Week 9, slide 28. Source slide.

Broadcast is scoped to a broadcast domain. IPv4 directed-broadcast forwarding is disabled by default under RFC 2644. IPv6 uses multicast instead of broadcast. Multicast delivery depends on group membership and supporting network mechanisms. None of these audience descriptions by itself promises that every intended receiver obtains the data.

Check: Does multicast simply mean sending to all computers connected to the Internet?

No. It targets a group, with delivery controlled by network support and membership. It is different from both one-destination unicast and scoped broadcast.

10. Protocols and layers divide responsibilities

A protocol defines formats and behavior: what can be sent, how a recipient responds, and what happens after a timeout or failure. Agreeing only on a message’s layout is not enough if each party expects the other to act first. Protocols make independently implemented systems cooperate.

The shipping analogy separates preparing a message from carrying its containers through intermediate stops. It is a model of responsibilities, not a literal implementation.
Figure 21. The shipping analogy separates preparing a message from carrying its containers through intermediate stops. It is a model of responsibilities, not a literal implementation. CSE101 Week 9, slide 30. Source slide.
A four-layer Internet model: application, transport, network and link. Physical signaling underlies the link communication.
Figure 22. A four-layer Internet model: application, transport, network and link. Physical signaling underlies the link communication. CSE101 Week 9, slide 31. Source slide.
What each layer contributes
LayerQuestion
ApplicationWhat does the data mean for this service?
TransportWhat endpoint-to-endpoint service is provided?
NetworkHow does an IP packet move toward its destination?
LinkHow is data carried over this local hop?
The original end-to-end schematic. Read intermediate addressing as next-hop delivery; ordinary forwarding does not replace the final destination IP. Its generic packet terminology simplifies several different data units.
Figure 23. The original end-to-end schematic. Read intermediate addressing as next-hop delivery; ordinary forwarding does not replace the final destination IP. Its generic packet terminology simplifies several different data units. CSE101 Week 9, slide 32. Source slide.

An application supplies data to a transport service, which uses network delivery and then a link. Added headers carry information for the relevant layers. At the destination, corresponding layers interpret their parts and deliver data upward. A router’s forwarding work does not require understanding whether the application bytes describe a temperature, a photograph or a command.

Check: Must a router understand LED=1 as “turn on the LED” to forward the packet?

No. That meaning belongs to the application. The router uses the information required for forwarding.

11. TCP and UDP offer different services

Choose a service, not a universal speed winner
PropertyTCPUDP
Application viewOrdered byte streamIndividual datagrams
Loss/order serviceRecovery and ordering, or connection failureNo built-in delivery or ordering guarantee
SetupConnection establishmentNo transport connection handshake
Application taskDefine message boundariesHandle missing or late datagrams as needed
The original simplified TCP/UDP comparison. “More efficient” is not a universal speed ranking; reliability, security and application correctness are different properties.
Figure 24. The original simplified TCP/UDP comparison. “More efficient” is not a universal speed ranking; reliability, security and application correctness are different properties. CSE101 Week 9, slide 35. Source slide.

TCP provides an ordered byte stream. The application must define messages within that stream: one write does not guarantee one matching read. UDP retains datagram boundaries but does not itself guarantee delivery or order. A higher-level protocol can add reliability above UDP. Neither choice alone establishes encryption or proves that a command was executed.

Imagine data pieces A, B and C, with B lost. TCP can recover the missing bytes and present an ordered stream; persistent failure can instead terminate the connection. With three UDP datagrams, the application must decide what missing B means. These lettered pieces are a conceptual trace, not actual TCP sequence-number fields.

Check: If a receiver reads five bytes from TCP, does that establish that it received one complete application command?

No. The application needs its own framing rule, such as a length or delimiter. Stream delivery does not identify command boundaries for it.

12. Application roles and application evidence

Client/server and peer-to-peer describe application roles. They do not specify a cable arrangement or require a server process to run continuously forever.
Figure 25. Client/server and peer-to-peer describe application roles. They do not specify a cable arrangement or require a server process to run continuously forever. CSE101 Week 9, slide 36. Source slide.

A client requests a service; a server provides it while available. Peer applications can both request and provide resources, and can still use centralized discovery services. A physical computer may run several such roles. The network topology and the application relationship are separate descriptions.

Suppose a controller receives the text LED=1. The application must define the grammar, allowable values, framing and response. A reply saying “accepted” is evidence of acceptance under that protocol; it is not automatically a physical measurement showing that the LED emits light. This recalls Week 6’s distinction between an output command and its observed effect.

A serial link can carry the same text without being an IP network. In the lab, communication support is supplied so the programming focus can remain on bounded text and memory. Names, DNS, HTTP and browsers form Week 10’s network continuation. Security mechanisms have their own later treatment.

Check: Why might a command identifier be useful if an application retries after no reply arrives?

The receiver may already have acted even though the reply was lost. A defined identifier and duplicate-handling policy can help distinguish a retry from a new request. Exact behavior belongs to the application protocol.

13. A pointer is an object that stores an address

C pointers concern objects in program memory. An IP address is not a C pointer, and network delivery is not memory dereferencing. The common lesson is to identify precisely what an address refers to and which rules make using it valid.

The pointer object stores an address referring to another object. The arrow depicts that relationship, not an extra physical wire.
Figure 26. The pointer object stores an address referring to another object. The arrow depicts that relationship, not an extra physical wire. CSE101 Week 9, slide 40. Source slide.
Three quantities: the pointer’s own address, the address stored in it, and the value at the target. The hexadecimal labels are conceptual, not promised real memory locations or alignment.
Figure 27. Three quantities: the pointer’s own address, the address stored in it, and the value at the target. The hexadecimal labels are conceptual, not promised real memory locations or alignment. CSE101 Week 9, slide 41. Source slide.
Read notation in context
ExpressionMeaning
int *p;Declare p as a pointer to int; this local declaration alone does not initialize it.
&xObtain x’s address.
p = &x;Store that address in p.
*pDesignate the int object to which p points.
&pObtain the address of the pointer object itself.

The star in a declaration describes a type; in an expression it dereferences a pointer. The address-of operator obtains an address rather than making a copy of the target’s value. A pointer also has a type, which affects valid accesses and arithmetic. Do not treat an address diagram as permission to read arbitrary numbered memory.

Check: If p stores the address of x, are p and x the same object?

No. p is a pointer object; x is its target. The expressions x and *p designate the same target, but p has its own storage and value.

14. Trace the pointer and its target separately

#include <stdio.h>

int main(void) {
    int x = 5;
    int *p = &x;
    *p = 8;
    printf("%d %d\n", x, *p);
    return 0;
}
State after each statement
Statementxp*p
int x = 5;5Not declaredNot applicable
int *p = &x;5Address of x5
*p = 8;8Address of x8

The output is 8 8. The write through *p changes x because both designate the same int. The pointer value remains the address of x. Assigning a different address to p would instead redirect future accesses without changing either target’s value by itself.

Original address-and-dereference example. ip first points to x, then to z[0]. z is uninitialized here: obtaining its element’s address does not initialize or read that element.
Figure 28. Original address-and-dereference example. ip first points to x, then to z[0]. z is uninitialized here: obtaining its element’s address does not initialize or read that element. CSE101 Week 9, slide 45. Source slide.

In the original fragment, y receives x’s value through *ip, and *ip = 0 then changes x. Finally ip is redirected to the first element of z. A later read from that uninitialized element would require initialization first. Separate “form an address” from “read the object at that address.”

Check: After p = &x, does changing x force us to refresh p to read the new value?

No. p still designates the same object. A later *p reads that object’s current value.

15. Passing an address still passes a value

The scalar swap changes only its local copies. The label WRONG means ineffective for changing the caller; it is not a claim that the syntax is invalid C.
Figure 29. The scalar swap changes only its local copies. The label WRONG means ineffective for changing the caller; it is not a claim that the syntax is invalid C. CSE101 Week 9, slide 46. Source slide.

Week 7 showed that ordinary C arguments pass values. Calling a function with a and b gives scalar parameters their values; assigning those parameters does not assign the caller’s objects. To change the objects deliberately, supply their addresses and use pointer parameters.

The caller uses swap(&a, &b). The copied pointer values inside the function still refer to the caller’s original objects.
Figure 30. The caller uses swap(&a, &b). The copied pointer values inside the function still refer to the caller’s original objects. CSE101 Week 9, slide 47. Source slide.
The original pointer swap stores one value temporarily before overwriting its original location.
Figure 31. The original pointer swap stores one value temporarily before overwriting its original location. CSE101 Week 9, slide 48. Source slide.
#include <stdio.h>

void swap(int *px, int *py) {
    int temp = *px;
    *px = *py;
    *py = temp;
}

int main(void) {
    int a = 5, b = 8;
    swap(&a, &b);
    printf("%d %d\n", a, b);
    return 0;
}
Trace of the caller’s objects
Stageabtemp
Before call58Not declared
temp = *px585
*px = *py885
*py = temp855

Both pointers must designate existing writable int objects with values that can be read. The temporary preserves the first value while its original location is overwritten. C has not switched to C++ reference parameters: it copies address values and uses those copies to access the original objects.

Check: What happens with swap(&a, &a) for this implementation?

The temporary stores a’s value, then each assignment writes that same value back to the same object. a is unchanged. Two parameters can refer to one object; they need not designate distinct objects here.

16. Arrays and pointers are related but distinct

An array consists of consecutive elements with a fixed extent. Each element has an address.
Figure 32. An array consists of consecutive elements with a fixed extent. Each element has an address. CSE101 Week 9, slide 50. Source slide.
pa is a pointer to the first element of a. All four original components are retained; the array itself is not a reassignable pointer variable.
Figure 33. pa is a pointer to the first element of a. All four original components are retained; the array itself is not a reassignable pointer variable. CSE101 Week 9, slide 51. Source slide.

In many expressions, an array is converted to a pointer to its first element. Exceptions include using the array as the operand of sizeof or unary &. For a valid index i, pa[i] means *(pa + i). This is why a function can use a pointer to access caller-owned array elements without copying the whole array.

Pointer arithmetic steps in elements of the pointed-to type. If p points to an int element, p + 1 refers to the next int element, not necessarily the next byte. The size of int is implementation-dependent. A pointer parameter does not retain the array’s element count, so a function still needs a correct length or another valid boundary convention.

For int a[10] and int *p = a
ExpressionRule
p + 1Points to the second element.
*(p + 3)Accesses a[3].
p + 10May be formed as a one-past pointer; must not be dereferenced.
p + 11Outside the permitted arithmetic range for this array.
Check: May we read *(p + 10) just because p + 10 is a permitted one-past pointer?

No. Forming that boundary pointer is allowed; accessing an element through it is not. There is no eleventh element in a ten-element array.

17. A non-null pointer is not enough

Valid access depends on initialization, target lifetime, type, bounds and whether the requested read or write is permitted. An uninitialized automatic local pointer has no usable initial target. A null pointer intentionally refers to no object and must not be dereferenced. A non-null pointer can still be invalid, for example after its target’s lifetime ends.

Returning the address of an ordinary automatic local variable does not keep the variable alive. Once the function returns, that object no longer exists for the caller to access. A familiar-looking numeric address does not repair the lifetime problem. Similarly, an address within an array is useful only for the permitted object and access; it is not a general permission to inspect neighboring memory.

When reviewing a pointer expression, ask: where did this pointer value come from, which object does it designate, does that object still exist, and is this access within its bounds? These questions are more reliable than assuming that a run which happened not to crash was correct. Dynamic allocation is a later topic.

Check: If a bad pointer access produces a plausible number instead of a crash, has it passed a validity test?

No. Undefined behavior can appear to work. Establish the language-level conditions for valid access rather than inferring them from one observed result.

18. A C string includes a terminator

A C string is a character sequence ending with the null character '\0'. The terminator occupies storage but is not counted in the string’s length. A buffer has a capacity whether or not its contents currently form a valid string. These are separate facts.

char buf[8] = "LED=1";
Index01234567
Stored characterLED=1\0\0\0

The first terminator is at index 5, so the string length is five and capacity is eight bytes. The remaining elements are zero-initialized by this initializer. In these ASCII-style examples each displayed character occupies one byte; in encodings such as UTF-8, a user-perceived character can involve multiple bytes, so byte length and character count need not agree.

Do not confuse the notations
NotationMeaning
'1'One digit character
"1"A character array containing the digit followed by a terminator
'\0'The null character, whose value is zero
NULLA null pointer constant used in pointer contexts
Check: Can a five-byte buffer contain LED=1 as a valid terminated C string?

No. The five visible characters use all five bytes, leaving no byte for the terminator. It can hold those bytes, but they are not a terminated string.

19. Writable arrays, literals and length

char buf[8] = "LED=1";
buf[4] = '0';        // now "LED=0"

const char *label = "LED=1";
// Read through label; do not modify the literal.

buf is a writable array initialized from a string literal. label stores an address through which the literal is read. Attempting to modify a string literal has undefined behavior, even in C environments where an assignment to a non-const pointer type might be accepted. Use a writable array when the characters need to change.

Capacity and initial string status
DeclarationCapacityInitial status
char a[] = "LED=1";6 bytesLength 5
char b[8] = "LED=1";8 bytesLength 5
char c[1] = "";1 byteEmpty string, length 0
char d[5] = "LED=1";5 bytesNo terminator; not a C string

The last initialization is allowed by C when the array fits the characters but not the terminator; it does not make subsequent string-library operations safe. C++ has different initialization rules for this case. Our runnable buffer examples allocate terminator space and avoid relying on that difference.

strlen requires an already valid terminated string; it is not a safe way to discover whether an arbitrary buffer has a terminator. Likewise, ordinary %s output and strcmp require appropriate terminated strings. Capacity must come from known storage or a trusted interface contract, not from guessing at pointer values.

Check: Why are sizeof(buf) and strlen(buf) different for this local eight-byte array?

sizeof(buf) gives the array’s full storage size, eight bytes. strlen counts characters before the first terminator, initially five. Inside a function receiving a pointer, sizeof that pointer would not recover the original array capacity.

20. Search for a terminator within known storage

int text_length(const char *s, int cap) {
    int i = 0;
    while (i < cap && s[i] != '\0') {
        ++i;
    }
    return i;
}

The contract requires cap ≥ 0 and access to at least cap readable character elements through s. Our examples always pass an existing array, including when cap is zero. If the returned value is below cap, it is the index of the first terminator and the string length. A result equal to cap means no terminator was found in the examined region. This is a status distinction, not proof that a terminated string has length cap.

Logical AND evaluates left to right and short-circuits. The bound is tested before s[i] is inspected. At i = cap the second operand is not evaluated, so the helper does not read s[cap]. Reversing the operands would lose that protection. The bound is still supplied by the caller; passing a value larger than accessible storage violates the contract.

Bounded traces
Input and boundResultMeaning
LED=1 followed by a terminator, cap 85Terminator found at index 5
Three bytes L, E, D; cap 33No terminator found
Same array; cap 22Only L and E inspected; no terminator
Same array; cap 00Nothing inspected; no terminator established
Check: If text_length(raw, 3) returns 3, is printf("%s", raw) now justified?

No. Equality with the bound reports that termination was not established. Do not pass the buffer to an operation requiring a C string on that evidence.

21. Use the result before comparing or printing

#include <stdio.h>
#include <string.h>

int text_length(const char *s, int cap) {
    int i = 0;
    while (i < cap && s[i] != '\0') {
        ++i;
    }
    return i;
}

int main(void) {
    char buf[8] = "LED=1";
    int n = text_length(buf, 8);
    if (n < 8) {
        printf("%s (%d)\n", buf, n);
        if (strcmp(buf, "LED=1") == 0) {
            puts("Command recognized");
        }
    } else {
        puts("No terminator in buffer");
    }
    return 0;
}

The program prints LED=1 (5), then Command recognized. It checks termination within known capacity before treating the buffer as a string. The result of strcmp is zero for equal content. Comparing two pointers with == instead asks whether their pointer values are equal; distinct arrays can contain identical text.

A receive helper intended to append a terminator must reserve space for it, commonly receiving at most capacity minus one data bytes. Its contract must also define truncation, framing and failure behavior. A bounded scan establishes termination only in the examined region; it does not verify the command grammar or prove that a receiving device acted on the command.

Useful buffer tests
CaseExpected interpretation
Terminator at index 0Valid empty string
Terminator in the last available byteValid, with no spare room for another character before it
No terminator in the boundDo not use as a C string
Correctly terminated unknown commandMemory format valid; application may reject its meaning
Check: Two separate arrays each contain LED=1. Which operation tests matching text?

strcmp(a, b) == 0, after both are known to be valid strings. Pointer equality is not a text-content comparison.

22. Optional reference: signaling and switching illustrations

Speaking and listening illustrate a physical channel. These photographs are analogies rather than network measurements.
Figure 34. Speaking and listening illustrate a physical channel. These photographs are analogies rather than network measurements. CSE101 Week 9, slide 67. Source slide.

A physical communication system carries information through a signal. Modulation changes a property of a carrier in accordance with information. The appropriate method depends on the channel, noise, spectrum and equipment. A protocol layer diagram does not remove these physical requirements.

The original list of possible reasons for modulation. These benefits depend on the system and method; they are not automatic guarantees for every modulation scheme.
Figure 35. The original list of possible reasons for modulation. These benefits depend on the system and method; they are not automatic guarantees for every modulation scheme. CSE101 Week 9, slide 68. Source slide.
Amplitude modulation varies the carrier amplitude with the message signal.
Figure 36. Amplitude modulation varies the carrier amplitude with the message signal. CSE101 Week 9, slide 69. Source slide.
Frequency modulation varies the carrier frequency with the message signal. Changes in spacing between oscillations show the changing instantaneous frequency.
Figure 37. Frequency modulation varies the carrier frequency with the message signal. Changes in spacing between oscillations show the changing instantaneous frequency. CSE101 Week 9, slide 70. Source slide.
The original modulation survey names analog and digital methods. I/Q is a representation used by multiple methods, not one mutually exclusive modulation family.
Figure 38. The original modulation survey names analog and digital methods. I/Q is a representation used by multiple methods, not one mutually exclusive modulation family. CSE101 Week 9, slide 71. Source slide.

The diagrams introduce ways to encode information physically. They should not be interpreted as saying that modulation always removes interference or universally improves quality. Pulse-width modulation connects to Week 6’s timing discussion, but an output-control example and a communication channel can have different design goals.

Two retained circuit-switching views: a crossbar mechanism and a selected path through a network.
Figure 39. Two retained circuit-switching views: a crossbar mechanism and a selected path through a network. CSE101 Week 9, slide 72. Source slide.
Message and packet switching apply store-and-forward ideas at different granularities. Virtual-circuit packet switching does not make each packet a dedicated physical circuit.
Figure 40. Message and packet switching apply store-and-forward ideas at different granularities. Virtual-circuit packet switching does not make each packet a dedicated physical circuit. CSE101 Week 9, slide 73. Source slide.

Whole-message storage and forwarding can require an intermediate device to hold a larger unit before forwarding. Packetization divides that unit into smaller pieces that can share links with other traffic. This reference taxonomy broadens the examples; the core distinctions remain reserved resources, shared transmission and explicit forwarding rules.

Check: Does calling a service a virtual circuit mean it uses the same physical reservation mechanism as the pictured crossbar?

No. The term can describe a logical packet-forwarding arrangement. Examine the resource and forwarding model rather than relying on the word circuit alone.

23. Further study and preparation

Explain circuit versus packet switching, separate bandwidth from latency, and identify the jobs of MAC addresses, IP addresses and ports. For C, draw a pointer and its target separately, trace swap through addresses, identify an array’s permitted range, and distinguish buffer capacity from a terminated string’s length. Lab 8 uses fixed bounded data before supplied Arduino transport; dynamic allocation, file APIs and independent network programming are outside this unit’s practice requirement.

All 56 image components in the current Week 9 deck are retained as 40 figures, preserving original credits and paired diagrams. Captions link to their slide locations and qualify historical simplifications. The illustrations support explanations; their presence does not add new implementation assignments.

Search courses