代写辅导接单-COMP2017 9017

欢迎使用51辅导,51作业君孵化低价透明的学长辅导平台,服务保持优质,平均费用压低50%以上! 51fudao.top

COMP2017 9017 Assignment 1

Due: 23:592April2025

Thisassignmentisworth10%ofyourfinalassessment

ThisassessmentisCONFIDENTIAL.©UniversityofSydney

Contents

1 Assignment1-[SEGfaultSOUNDboard]-10% 2

2 Introduction 4

3 Task 4

4 Structure 4

5 Functionality 5

5.1 Part1: WAVfileinteraction,basicsoundmanipulation . . . . . . . . . . . . . . . . 5

5.2 Part2: Identifyadvertisements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

5.3 Part3: Complexinsertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

5.4 [COMP9017ONLY]Part4: CleaningUp . . . . . . . . . . . . . . . . . . . . . . . 9

5.5 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

5.6 Globalassumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

6 Shortanswerquestions 10

7 Marking 11

7.1 Compilationrequirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

7.2 Teststructure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

7.3 Seededtestcases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

7.4 Markingcriteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

7.5 Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

1

COMP20179017

8 SubmissionChecklist 13

9 Appendix 15

9.1 Workedfunctionexample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

10 Versionhistory 17

1 Assignment 1 - [SEGfault SOUNDboard] - 10%

We strongly recommend reading this entire document at least twice. You are encouraged to ask

questions on Ed after you have first searched, and checked for updates of this document. If the

questionhasnotbeenaskedbefore,makesureyourquestionpostisoftype"Question"andisunder

"Assignment"category→"P1". Pleasefollowthestaffdirectionsforusingthequestiontemplate.

It is important that you continually back up your assignment files onto your own machine, flash

drives, external hard drives and cloud storage providers (as private). You are encouraged to submit

yourassignmentregularlywhileyouareintheprocessofcompletingit.

Full reproduction steps (seed, description of what you tried) MUST be given if you are enquiring

aboutatestfailureorifyoubelievethereisabuginthemarkingscript.

Academic Declaration

By submitting this assignment you declare the following: I declare that I have read and understood

theUniversityofSydneyStudentPlagiarism: AcademicIntegrityPolicy,CourseworkPolicyandPro-

cedures, and except where specifically acknowledged, the work contained in this assignment/project

is my own work, and has not been copied from other sources or been previously submitted for award

orassessment.

I understand that failure to comply with the Student Plagiarism: Academic Integrity Policy, Course-

workPolicyandProcedurescanleadtoseverepenaltiesasoutlinedunderChapter8oftheUniversity

ofSydneyBy-Law1999(asamended). Thesepenaltiesmaybeimposedincaseswhereanysignificant

portion of my submitted work has been copied without proper acknowledgement from other sources,

including published works, the Internet, Generative AI where approved, existing programs, the work

ofotherstudents,orworkpreviouslysubmittedforotherawardsorassessments.

I acknowledge that I have reviewed and understood the University of Sydney’s guidelines on the

responsible use of Generative AI 1 and will adhere to them in accordance with academic integrity

policies.

I realise that I may be asked to identify those portions of the work contributed by me and required to

demonstrate my knowledge of the relevant material by answering oral questions or by undertaking

supplementarywork,eitherwrittenorinthetutorial,inordertoarriveatthefinalassessmentmark.

I acknowledge that the School of Computer Science, in assessing this assignment, may reproduce

1https://www.sydney.edu.au/students/academic-integrity/

artificial-intelligence.html

SystemsProgramming Page2of17

COMP20179017

it entirely, may provide a copy to another member of faculty, and/or communicate a copy of this

assignment to a plagiarism checking service or in-house computer program, and that a copy of the

assignment may be maintained by the service or the School of Computer Science for the purpose of

futureplagiarismchecking.

SystemsProgramming Page3of17

COMP20179017

2 Introduction

Audioisadigitisedwaveformrepresentingasound. Thesoundhasafrequency,whichcanbeencoded

at a given sample rate, affecting the quality of the audio (bitrate). These properties are encoded as

sequencesofamplitudevaluesovertimeinmemory.

Editing audio involves various operations such as clipping, inserting, and moving. Clipping refers

to selecting a portion of an audio file to keep or remove, inserting involves adding new portions at

specificpoints,whilemovingwouldchangeaportion’srelativepositionintime.

To support these operations, memory must be moved or copied and this can lead to inefficiencies.

Instead, an audio editor’s backend should use a shared backing store, where multiple operations ref-

erencethesameunderlyingdata.

3 Task

Youwilldevelopanaudioeditorbackendthatspecialisesinclippingandinsertingdatawithashared

backing - where changes made will affect all portions that reference it. Users of this software will

usethespecifiedfunctionprototypestoeditaudiowithsimpleoperations. Yourcodeshouldusedata

structures and algorithms to efficiently support editing as well as the ability to read and write to a

buffer.

4 Structure

TheaudiodataissourcedfromaWAVfile. TheentireWAVfileisreadandstoredintoabuffer.

A track is a data structure that copies a continuous region of the buffer. A track can represent the

entireaudioorspecificparts.

Any number of tracks can be created and the track can contain metadata that is useful to support the

operationsofthiseditor.

Eachtrackisrepresentedasanopaquedatastructurestruct sound_segthatyoumustcomplete,

accordingtotheneedsofyourimplementation. Eachstructurerepresentsoneaudiotrack.

// a track

struct sound_seg {

// TODO

};

Theaudioeditorexposesfunctionsinsection5,whichyouwillcomplete.

The functionalities of your program are divided into parts with varying levels of complexity. Each

parthasdifferentrequirementsandisaccompaniedbyspecificassumptions. Youshouldplanwellfor

aparticularlevelofachievementbeforecoding. Writinghelperfunctionsareencouraged.

Youarealsorequiredtoanswertheshortquestionsdescribedinsection6.

SystemsProgramming Page4of17

COMP20179017

5 Functionality

5.1 Part 1: WAV file interaction, basic sound manipulation

Conversionbetweenasoundfileandatrackisatwo-stepprocessinvolvinganintermediatebuffer.

FunctionstointeractbetweenWAVfilesandabuffer

void wav_load(const char* fname, int16_t* dest);

Thewav_load()functionreadsrawaudiosamplesfromthespecifiedWAVfilefnameandcopies

themintothedestinationbufferdest. TheWAVfile’sheaderisdiscardedduringtheloadingprocess,

leavingonlytherawaudiosampledataindest.

void wav_save(const char* fname, const int16_t* src, size_t len):

The wav_save() function creates or overwrite a WAV file, fname, using the audio samples pro-

vided in the source buffer src. The function constructs a valid WAV file, including the necessary

header,andwritestheaudiosamplestothefile.

Note: thisfunctiondoesnotfreethememorypointedtobysrc.

YoucanfindmoreabouttheWAVfileformathere.

REQ0.1:Anexistingsoundfilecanbeloadedfrom/toabuffer.

Testingmethod: sanity

ASM0.1:thesongwillalwaysbePCM,16bitspersample,mono,8000Hzsamplerate.

ASM 0.2: the provided path for wav_load(), wav_save() will always be valid. IO opera-

tionsarealwayssuccessful. destwillbelargeenough.

AllotherfunctionsdonotrequirereadingaWAVfile,andcanbeoperatedwithint16_tarrays.

Functionstointeractbetweenabufferandatrack

struct sound_seg* tr_init();

void tr_destroy(struct sound_seg* track);

tr_init() allocates and returns heap memory for a new empty track. This function may also

initialisethestructuretodefaultvalues.

tr_destroy()releasesallassociatedresourcesanddeallocatestheheapallocatedpointerto

struct sound_seg.

REQ1.1:tr_destroy()shouldfreeallmemorythetrackisresponsiblefor.

Testingmethod: random

SystemsProgramming Page5of17

COMP20179017

size_t tr_length(struct sound_seg* track);

tr_length()willreturnthecurrentnumberofsamplescontainedwithinthistrack.

void tr_read(struct sound_seg* track,

int16_t* dest, size_t pos, size_t len)

tr_read() copies len audio samples from position pos in the track data structure to a buffer

dest. destisanexternallyallocatedbufferwithguaranteedsizeofatleastlen.

void tr_write(struct sound_seg* track,

const int16_t* src, size_t pos, size_t len)

tr_write()functioncopieslenaudiosamplesfromabuffer,src,tothespecifiedpositionpos,

within the data structure track. Any previous data stored in the track for the range of pos to

pos+lenisoverwritten.

If the number of audio samples to be written to the track extend beyond the length of the track,

the track’s length is extended to accommodate the new data. Thus, a sequence of wav_load(),

tr_init(),andtr_write()effectivelytransfersaWAVfiletoatrack.

An ordering requirement when performing writes is to always write to lower indices before higher

ones. Thisisonlyrelevantfor5.3onwards.

REQ2.1:readsandwritesmakeacopyofdatafrom/tobuf.

Testingmethod: sanity

REQ2.2:writeindicesbeyondthelengthofatrackincreasesitslength.

Testingmethod: random

Youshouldmakethefunctionalityoftr_init(),tr_destroy(),tr_length(),tr_read(),

tr_write() your first priority. As the marking script uses them to check the behaviour of other

functions. Checksection7formoredetails.

bool tr_delete_range(struct sound_seg* track, size_t pos, size_t len)

tr_delete_range() removes a portion from a track. The portion to remove begins at pos and

spanslensamples. Afterdeletion,subsequentreadsofthistrackreturnthesamplesjustbeforepos,

immediately followed by those at pos + len, effectively skipping the removed portion. On suc-

cess, delete_range returns true. A failure case exists if tr_insert() (5.3) is implemented,

andshouldreturnfalse.

Note: Samples removed by tr_delete_range() do not necessarily have to be freed from mem-

oryimmediately,butshouldbefreedwhentr_destroy()iscalled.

REQ3.1:readsandwritesoverdeletedportionactasifadjacentpartsarecontinuous.

Testingmethod: random

Prerequisites: REQ2.2

SystemsProgramming Page6of17

COMP20179017

Part1Checklist

1. Programisabletocompilethroughmakefile.

2. Usingamainfunction,programisabletoreadaWAVfile.

3. Usingamainfunction,programisabletowav_load()andwav_save().

4. Programisabletodynamicallycreateemptytracks.

5. lengthandreadisfunctional.

6. writeisfunctional.

7. delete_rangeisfunctional.

5.2 Part 2: Identify advertisements

There are different kinds of sound represented as audio and as with all computer science problems,

searching is essential. A search may identify a song of a bird in a natural setting, a musical tune,

or even spoken words. Fortunately, there are algorithms such as Cross Correlation2 that allow us to

analysetwodigitalwaveformsandcomputetheirsimilarity. Effectivelyallowingyoutodetermineif,

andwhere,onesoundappearsinanother.

Inthemodernworld,audiomediaisoftenaccompaniedwithanadvertisement(ad). Thisisunwanted

noiseandwedonotacceptthis. YouwillidentifyandremovetheseadsusingCrossCorrelation.

Youaretocreateafunctiontosearchfortheexistenceandlocationsofanadwithinatargettrack.

char* tr_identify(const struct sound_seg* target,

const struct sound_seg* ad)

Returnsadynamically-allocatedstringintheformatof","indicatingthestartand

endindicesoftheadoccurrenceinthetarget,inclusive. Iftherearenoads,returnanemptystring. If

there are multiple ads, return a string consisting of all the index pairs, separated by a single newline

character\n,suchas",\n,\n,"

REQ 4.1: tr_identify() is able to identify potentially-multiple, non-overlapping occur-

rencesofadintarget.

Testingmethod: sanity

Prerequisites: REQ2.2

Functionalityistestedbydirectlyoverwritingportionsofthetargetwithcopiesofthead,ensuring

identicalamplitudes. Theadswillalwayshavethesameamplitudeandthereisnoscalingneeded.

Functionalityistestedbycopyingmultipleadsovertarget,withtheiramplitudevaluessummed."

Similarity is quantified by comparing correlation of the overwritten portion with the ad’s autocorre-

lation (cross correlation with the itself) at 0 relative time delay. As the reference, zero delay, this is

100%match. Aportionissaidtomatchiftheadisatleast 95%ofthereference.

ASM4.1:Theoccurrencesofadsintargetwillbenon-overlappingandsufficientlyclear.

The return method for tr_identify() function is poorly designed. You may be asked to address

thisissuewithanexplanation. Seesection6formoredetails.

2correlationwithsignalsrequirestakingthecomplexconjugate,butasweareworkingwithrealsignals,it

canbeignoredandindividualsamplessimplymultiplied.

SystemsProgramming Page7of17

COMP20179017

Part2Checklist

1. Abletocomputeautocorrelation,thereference.

2. Abletocomputecross-correlationandreturnstringvalue(s).

5.3 Part 3: Complex insertions

Thetruevalueoftheeditorbackendcomesfrommixingandclippingaudio.

void tr_insert(const struct sound_seg* src_track,

struct soung_seg* dest_track,

size_t destpos, size_t srcpos, size_t len);

tr_insert()performsalogicalinsertionofaportionfromasourcetrackintoadestinationtrack.

The portion to be inserted are len samples beginning at position srcpos in src_track. The

insertionpointisatpositiondestposindest_track.

Afterinsertion,dest_track’sdatabeforedestposremainsunchanged,followedbytheinserted

portion,andthentheremainingoriginaldatafromdest_track.

Note: Thisfunctionisconceptuallytheinverseofdelete_range().

Thisconsequenceofatr_insert()operationresultsinaparent-to-childrelationship. Theparent

(src) and the child (dest) share the same portion of data. If the data persists in both parent and child

without changes, the data need only be stored once. Hence, both portions have shared backing store.

Furtherinsert()operationsperformedontheparentorchildsimilarlyextendthissharedbacking,

such that tr_write() to one sample in a portion of one track could result in changes across many

othertracks.

Note: for cases of self-insertions. The portion is determined at the time tr_insert() is called,

beforetheportionisinserted. Thus,insertingaportionintooneselfiswell-defined.

REQ5.1:tr_insert()insertsareferencecopyofsrc’sportionintodest

Testingmethod: random*. Duetocomplexityofthisfunction,extratieredrestrictionshavebeen

laidout-youmayfindthattheysignificantlydecreaseprogrammingcomplexity:

5.1.1: Every sample in the parent to be inserted, and samples adjacent destpos, shall not

alreadybeaparentorchildthemselves.

5.1.2: Everysampleintheparenttobeinsertedshallnotalreadybeaparentorchildthemselves.

5.1.3: Samplesadjacentdestposshallnotalreadybeaparentorchild.

5.1.4: Samplesadjacentdestposshallnotalreadybeaparent.

5.1.5: Everysampleintheparenttobeinsertedshallnotalreadybeachild.

5.1.6: Norestrictions.

Prerequisities: allotherrequirements

Because the function tr_insert() operates on the same track, other functions must have stricter

requirementsforthefunctiontooperatecorrectly.

Forfunctionstr_read()/tr_write():

REQ2.3:changes(write)toachildportionmustbereflectedintheparent,andviceversa

SystemsProgramming Page8of17

COMP20179017

Testingmethod: random

Forfunctionstr_delete_range()/tr_destroy():

REQ 3.2: A parent portion may not be deleted if it has children. Attempts to do so return

false. tr_destroy()nonethelessremovestheportion.

Testingmethod: random

ASM 0.3: tr_destroy() will only be called at the end of the program, on all tracks to free

memory.

Youshouldusealinkeddatastructuretoimplement tr_insert.

Part3Checklist

1. Implement the trivialised version of tr_insert() by copying sample data (wasteful data

duplication).

2. Understandandmodelthebehaviouroftr_insert().

3. Implementtr_insert()at5.1.1level.

4. Ensurerequirementsforotherfunctionshold.

5. Implementtr_insert()at5.1.6level.

5.4 [COMP9017 ONLY] Part 4: Cleaning Up

Toomanytr_insert()operationscanleadtoconfusingparent-childrelationships. Thefollowing

functionaimstoalleviatethisissue.

void tr_resolve(struct sound_seg** tracks, size_t tracks_len);

tr_resolve()conditionallybreaksparent-childrelationshipsforspecifiedtracks. Givenanarray

of track references tracks, if a portion Pi is a direct parent to another, Pj, and both portions can be

foundintracks,thiswillbreaktheirrelationship,suchthat:

• Pjisnolongerachild.

• Piisnolongeraparentifitdoesnothaveotherchildren.

Inthetrivialcase,ifbothPiandPjexistintrackT andtr_resolvewascalledonT,thetrackwill

effectivelybeflattenedandthepreviouslysharedmemoryofthoseportionsbecomesduplicateddata.

ConsidertracksA,B,C,D,Ewithasharedportionbetweenthemandthecorrespondingparent->child

relationships as A->B, B->C, C->D, A->E. If tr_resolve was called on {B, C}, then after

callingtr_resolve():

• B->Cnolongerexists.

• A->Bstillexists,asAwasnotprovided. Bysimilarlogic,C->Dalsoexists.

• A->Estillexists,asneitherAnorEwereprovided.

• TheportioninBcannowbedelete_range’d,asitisnolongeraparent.

• Aisaparentmaintainingtheportion(asbefore)

SystemsProgramming Page9of17

COMP20179017

• Cbecomesaparentmaintainingtheportion(duplicatedasaresultofbreakingfromB)

tr_resolve()hasnoweffectivelysplitthesharedbackingstoreintotwo. TheportionsinA,B,E

inone,andC,Dinanother.

Iftr_resolve()wascalledon{A, C}or{A, E},althoughtheysharethesamememoryback-

ing,nothingwillhappenastheydonothaveadirectparent-childrelationship.

REQ 6.1: tr_resolve() removes every direct parent-child relationship if the list provided

containsbothparentandchild.

Testingmethod: random.

Testcaseisprivate. Pleasewriteyourowntoverify.

Prerequisites: REQ5.1

5.5 Performance

Memory usage and leaks are tracked in your program by dynamically replacing symbols malloc,

calloc,reallocandfree.3 Youshouldonlyusetheabovestandarddynamicmemoryallocation

functions.

Randomtestcasesfortr_insert()enforceamaxdynamicmemoryusage.

5.6 Global assumptions

Tosimplifylogic,youcanignoreindexboundschecking.

ASM 7.1: indices covered by tr_read(), tr_delete_range(), and srcpos and len in

tr_insert()arealwaysinrange.

ASM 7.2: The starting position for tr_write() and destpos for tr_insert() ranges

from0tothetargettracklength,inclusive.

6 Short answer questions

As part of the in-tutorial code review in week 8, you are required to analyse your code and prepare

for two of the below questions. You must supplement your answer with references to your code.

The examiner will also ask follow-up questions based on your response. COMP9017 students must

answerQ4.

Q1: Howmayyouredesignthefunctionprototypeforidentify,suchthatitmorerobustlyreturns

thelistofadstartsandends?

Q2: Referring to REQ 1.1, how did you identify which track is responsible for which memory, and

how did you ensure that all memory is freed? If you were not successful in ensuring, how did you

planto?

3Notethatsomefunctions,likeprintf,alsousedynamicmemory. Donotcalltheminyoursubmission.

SystemsProgramming Page10of17

COMP20179017

Q3: [COMP2017 ONLY] Explain the time complexity of your tr_insert() and tr_read()

byreferringtotherelevantpartsofyoursourcecode.

Q4: Demonstrate how you constructed test cases and the testing methods used to confirm your pro-

gram functions correctly. If you answer this question, the testcases must be in your final submission

inafoldernamedtests,andalltestsshouldberunbythefiletests/run_all_tests.sh.

7 Marking

7.1 Compilation requirements

Using the make program, your submission should compile into an object file, which the user/marker

willutilise.

Yoursubmissionmustproduceanobjectfilenamedsound_seg.ousingthecommand

make sound_seg.o. The marking script will compile this into a shared library to be used. Thus,

theflag-fPICmustbeadded.

You are free to (and encouraged to) add extra build rules and functions for your local testing, such as

amainfunctionordebugflags. ASANisencouragedduringlocaltesting,butmustnotbeaddedto

yourfinalsubmission. 4

When marking your code will be compiled and run entirely on the Ed workspace. The marker will

run the aformentioned make commands to compile your program and run the executable. If it does

not compile on the environment, then your code will receive no marks for your attempt. When

submittingyourworkensurethatanybinaryfilesgeneratedarenotpushedontotherepository.

7.2 Test structure

After your object file is compiled into a shared library, python scripts (ctypes) are used to interact

withthefunctionsdescribedinspec. Inmostcases,thescriptisresponsiblefor:

• Creatingtemporarydata,

• Orchestratingcallingoffunctions,

• Comparingreturneddatawithexpectedvalues.

This is used for both sanity and random tests. Thus, you can think of the test inputs and outputs as

not given from a separate program (and waits for you own program to respond and exit), but rather

driveninthesameprogram,andtheoutputsarevalidatedbeforeyourprogramends.

7.3 Seeded testcases

All*_randomtestcaseshavethefollowingstructure:

4ThemarkingscriptwillattempttoremoveASANandaddPICduringcompilationbyappendingtheflags

-fno-sanitize=all -fPIC -Wvla -Werror. Ifthisisnotsuccessful,markingwillsilentlyfail.

SystemsProgramming Page11of17

COMP20179017

1. randomamountoftracksarecreated.

2. arandomarrayiswrittentoeachtrackusingtr_write().

3. arandomoperationbetweentr_write(),tr_delete_range(),andtr_insert()is

chosenifallowed.

4. tr_length()andtr_read()isdoneonrandomtracksandverifiedagainstexpectedval-

ues.

5. repeatrandomoperationandverificationforsomecycles.

6. all tracks are properly managed where tr_destroy() is called and implemented correctly.

Memoryleakcheck.

7. returnvalueischecked(non-zeroindicatesfailure). 5

Ifafailureisreached,themarkingscriptattemptstoreturntheinputsetthatcausedthefailure,which

youcanuselocallytodebug. Additionally,youarealsoabletomanipulaterandomtestcasesforyour

owntesting-detailshavebeenprovidedintheEdStemlesson.

For each random testcase in a submission, the seed used is included in the feedback section and can

be used to deterministically regenerate inputs. During the marking phase, a predetermined set (15+)

of seeds will be used and the percentage passed will become your final mark for a specific test. The

assignmentEdStemlessonprovidesmoredetailsforconfiguringrandomtestcases.

From rudimentary analysis, passing insert_no_overlap_*_random for a single seed implies

youwillalsopass95%ofotherseeds,andpassingotherrandomtestsforasingleseedimplies99+%.

Ifyouonlysubmitonceandall7randomtestcasespass,youwouldexpectaHDmarkwithverylow

variance. Submitting more than once, and thus testing using multiple seeds, greatly increases this

confidence level; but even if you only submit once, the confidence of passing the reserved seeds far

exceedtheconfidenceofpassingaprivatetestcaseifonlyastatictestcaseisused.

Allfinaltestinputswillbepostedafter17April.

7.4 Marking criteria

The assignment is worth 10% of your final grade. This is marked out of 20, and breaks down as

follows. Formarksawardedpertestcase,pleaserefertoEdstem.

Marks Item Notes

3/20 CodeStyle Manualmarking

5/20 5.1Correctness Automatictests

4/20 5.2Correctness Automatictests

8/20 5.3Correctness Automatictests

For style, refer to the style guide. You will also be marked based on the modularity and organisation

of your code. For full marks, code should be organised in multiple source files, and use modular,

task-specificfunctions. Organiseddatastructuresareessentialhere. Stylemarkingisonlyappliedfor

reasonableattempts(5.1Correctness).

[COMP9017ONLY]9017studentswillhavetheirabovemarksscaledby0.9. 5.4Correctnesscounts

for2/20.

5Thus,pleasedon’treturnanonzerovalueuponprogramexit.

SystemsProgramming Page12of17

COMP20179017

7.5 Restrictions

To successfully complete this assignment you must (submissions breaking these restrictions will re-

ceiveadeductionofupto6marksperbreach):

• ThecodemustentirelybewrittenintheCprogramminglanguage.

• Mustusedynamicmemory.

• Freealldynamicmemorythatisused.

• NOT useanyexternallibrariesotherthanthoseinlibc.

• NOT useVLAs.

• NOT have unclean repositories. This means no object, executable, or temporary files for any

commitintherepository,justyourfinalsubmission.

• Only include header files that contain declarations of functions and extern variables. Do not

definefunctionswithinheaderfiles.

• Mustusemeaningfulcommitsandmeaningfulcommentsoncommits. 6

• Otherrestrictedfunctionsmaycomeatalaterdate.

• AnyandallcommentsmustbewrittenonlyintheEnglishlanguage.

The red flag items below will result in an immediate zero. Negative marks can be assigned if

you do not follow the assignment description or if your code is unnecessarily or deliberately

obfuscated:

• Anyattemptstodeceiveordisruptthemarkingsystem.

• Use any of the below functions. You shouldn’t need to use these functions at all in your pro-

gram,andyouaredoingsomethingterriblywrongifyouare.

– _init,atexit(2),_exit(2),_Exit(3)

– dlopen(3),dlsym(3),dlclose(3)

– fork(2),vfork(2),execve(2),exec*(3),clone(2)

– kill(2),tkill(2),tgkill(2)

– getpid(2),getppid(2),ptrace(2),getpgrp(2),setpgrp(2)

8 Submission Checklist

• Submissionhaveavalidmakefilewiththerulesound_seg.oandcompiles.

• Reviewedallrestrictions(notallareautomaticallychecked)

• Programisorganisedintomultiplesourceandheaderfiles(forlargerprograms).

• Notincludeanyobjectfile,binary,orjunkdatainyourgitrepo.

• IfyouhaveusedAI,references.zipformattedaccordingtoEdStemslidessubmittedwith

sourcecode.

6"forcingtheseedofatestcase"doesnotcountasvalidcommit. Mustcitereasonandidentifiedfailure.

SystemsProgramming Page13of17

COMP20179017

Glossary

assumption shortened: ASM.Apropertythatisexternallyguaranteedtobetruewhenyourprogram

is run. When testing, situations which violate this property will not happen. Thus, handling

behaviour that falls outside of an assumption (e.g. out of bounds read) will not give you

marks. 4

child Aportionthathasbeeninsertedfromanotherpartofatrack. Theportionisthechildtothe

portionthatitwas copiedfrom. Asamplemay onlybelongtooneparent. writestothechild

mustbereflectedintheparent. 8–10,14

parent A portion that has been inserted into another part of a track. The portion is the parent to

only portions that exist due to that insert. A portion may be a parent to multiple children.

writestotheparentmustbereflectedinthechilden. Afterinserting,itispossibleforaparent

portiontobenotcontiguous. 8–10

portion refers to a part of a track. Contains zero or more samples. Portions are defined logically

ratherthantheirindicesinatrack. Indicesofportionsamplesmaychangeifadelete_range

orinsertmodifiesthelengthofthetrack.. 6–8,14

random Property-based testing that test for the specified requirement, with inputs restricted by as-

sumptions. Inthisassignment,thepythonlibraryhypothesisisused. 5,8,11,12

requirement shortened: REQ. A property that your program is expected to hold when run. Marks

aregivendependingonhowwellyourprogramholdsthem. Mostrequirementsinparts2and3

haveprerequisites,propertiesthatneedtoholdbeforethethecurrentrequirementisconsidered.

4

sample Audioisadigitisedwaveformrepresentingasound. Thesoundhasafrequency,whichcanbe

encoded at a given sample rate. A sample is simply a numberic value representing the strength

of sound at a particular time. In the context of this assignment, the data type for a sample is

int16_t.. 5,7,14

sanity A directed testcase targeting a specific functionality. For example, a sanity test for REQ 2.1

may be to create a track, write into it, modify the original buffer, then verifying if the buffer

andthetrackcontentsaredifferent. Randomnessmaystillbeinvolved. 5,11

sharedbackingstore A shared backing store is a memory management technique where multiple

references to the same underlying data are used instead of copying or moving memory. . 4, 8,

10,15

track A struct sound_seg object. It represents the user’s view of the API as users mix the

differentobjectstogether. 4–7,10,12,14

SystemsProgramming Page14of17

COMP20179017

9 Appendix

9.1 Worked function example

Parent track

Child track

Figure 1: This example uses two tracks. They are created and filled using a sequence of tr_init,

andtr_writeofdata.

len len+50

Parent track Parent track

tr_write(parent, data, len, 50);

child_len

Child track

Figure 2: Either track can be extended via a call to tr_write. By calling write on the end of the

parent,newdataiseffectivelyconcatenated.

spos1 spos1+len parent_len

Parent track s1

tr_insert(parent, child, spos1, dpos1, len);

dpos1 dpos1+len

Child track d1

child_len+len

Figure3: Theinitialinsertextractsaportions1fromtheparent,andplacestheportionintothechild,

alsoextendingit. Duetosharedbackingstore,thereisalogicalrelationshipbetweens1andd1.

SystemsProgramming Page15of17

COMP20179017

spos1 spos1+len parent_len

Parent track s1 s2

spos2 spos2+len

tr_insert(parent, child, spos2, dpos2, len);

child_len+len*2

Child track d2 d1

dpos2 dpos2+len dpos1+len dpos1+len*2

Figure 4: A second, overlapping insert occurs, placing d2 before d1. Note that 1) while the child is

extended and indices for d1 changed, the logical relashionship remains. 2) the overlapping samples

of s1 and s2 means that parts d1 and d2 (highlighted in purple), even though unrelated, also share

samples.

spos1 spos1+len parent_len

Parent track s1 s2

spos2 spos2+len

tr_delete_range(child, dpos2+len-5, 10);

child_len+len*2-10

Child track d2 d1

dpos2 dpos2+len-5 dpos1+len-10 dpos1+len*2-10

Figure 5: tr_delete_range will fail if any of the specified samples is a parent (in this case, s1

and s2. Child samples such as a part of d2 can still be deleted (the command deletes the last 5

samples of d2, and 5 samples after the end, for 10 total). Because d2 no longer contains the last 5

samples, The last 5 samples of s2 (in red) also stops being a parent; there is no immedate change,

but those samples can now be deleted. Again noticed how the indices for d1 were shifted without

impactingtheparent-childrelationship.

SystemsProgramming Page16of17

COMP20179017

10 Version history

Weaimtoresolveallspecupdateswithinthefirst3-5days.

19/03/2025-11:12

• Clarifythatmostfunctionsonlyinteractwithint16_tbuffers,notWAVfiles,multipletimes

inthespec

• clarifieddefinitionofsample,inthecaseofthisassignmentanalogustoint16_t.

• If you plan to answer Q4 short answer, you must upload a folder called tests with your tests

inthem.

• Addedsomebannedfunctionrestrictions,whichalreadyexistinthetestcase.

• Addedprerequisitetotr_resolve

• Reworded tr_identify from "ads overwriting target" to "ads inserted on top of target".

Suchthattheadsinthetargetaren’texactlythesame.

14/03/2025-10:35

• Createdversionhistory.

• Addeddetaileddescriptionofmarkingprocesswithpython.

• ReworddestinREQ5.1todestpos.

• correctreturnvalueoftr_destroyfrombooltovoid.

• Definewhatanuncleanrepois.

• ClarfiedthatcodemustbewritteninC,andcompileinEdStem.

• Improvewordingoftr_resolvefrom"previouslysharedmemorybecomesduplicateddata"

to "previously shared memory of those portions becomes duplicated data", to clarify only spe-

cificportionsareflattened.

• Createdsubmissionchecklist.

• Addedsuggestionsofextramakefilerulesforstudents’owntesting.

• Added linked to EdStem slides about manipulating EdStem testcases, and submitting AI refer-

ences.

• Added-Wvla -Werrorasimplicitcompilationflags.

SystemsProgramming Page17of17

51作业君

Email:51zuoyejun

@gmail.com

添加客服微信: Fudaojun0228