Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Working on a program where my task is to implement a library (as a set of source and header files, documentation, and a Makefile) that

Working on a program where my task is to implement a library (as a set of source and header files, documentation, and a Makefile) that provides a few useful functions for working with a counted string data structure.

And one of the functions that needs to be written is described below but I am having a little difficulty writing it. Program needs to be written in C.

void kstrfree(kstring str)

Frees the memory to which str.data points. Should correctly handle any kstring created with either kstralloc() or kstrfrom(), including those with length 0.

Note: Since the kstring is passed by value, setting its data pointer to NULL would not be reflected in the caller. This means that it is the caller's responsibility not to re-use the kstring it passed to this function.

Here is some code I have already done that might be needed:

#include #include #include typedef struct kstrings{ char *data; int length; }kstring;

kstring kstralloc(size_t nbytes){

int i; kstring new_kstring; // creating a object of type ksting new_kstring.data = malloc(nbytes); // allocating nbytes of memory to create string of length nbytes if (new_kstring.data == NULL && nbytes!= 0){ printf("There is an error allocating memory "); abort(); } new_kstring.length = (int)nbytes; // setting length member to size mentioned using nbytes // initializinf by filling it with nbytes copies of the null byte ('\0'). for (i= 0;i

kstring kstrfrom(const char *cstr) { //first, find the length of the c-string int len = 0; while (cstr[len] != '\0') { len++; } len++; //null terminator counts in length //now allocate memory for the new kstring kstring result = kstralloc(len); //since we have the right length, save it in the kstring result.length = len; //copy the data over for (int i=0;i<(len-1);i++) { result.data[i] = cstr[i]; }

return result; }

// Driver program

int main(){ size_t i = 50; kstring kstr = kstralloc(i); // Allocating memory for data member

strcpy(kstr.data, "Testing data member"); printf("Data : %s Lenght : %d",kstr.data,kstr.length); kstrfree(kstr); return 0; }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Probabilistic Databases

Authors: Dan Suciu, Dan Olteanu, Christopher Re, Christoph Koch

1st Edition

3031007514, 978-3031007514

More Books

Students also viewed these Databases questions