Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

COMPUTER SCIENCE, I have some pseudo code of what the function needs to do. This

ID: 3666467 • Letter: C

Question

COMPUTER SCIENCE, I have some pseudo code of what the function needs to do. This is in C

function

kstring kstralloc(size_t nbytes)

Creates and returns a new kstring object with the specified length. The .length member of the returned kstring should be equal to nbytes. The .data member should be a pointer to newly-allocated memory; the memory should be initialized by filling it with nbytes copies of the null byte ('').

If there is an error allocating memory, this function should call abort() or throw an uncaught exception.

Note: your program must support allocating (and subsequently using and freeing) zero-byte strings.

Explanation / Answer

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

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 ('').
   for (i= 0;i<nbytes;i++)
       new_kstring.data[i] = '';   
  
   return new_kstring;
}

void kstrfree(kstring freeMe){
   free(freeMe.data);

}

// 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;
}

Output:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote