I'm working on an assignment that handles text and operations on the text. What I have so far is
Code:
//tests.c
//Compile: gcc -Wall -Werror -O -o text textbuffer.c tests.c
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "textbuffer.h"
void initialize (void);
int main (int argc, char *argv[]) {
initialize ();
return EXIT_SUCCESS;
}
void initialize (void) {
{
TB TestSubject;
printf("\nTest 1: Initialize with text \"abcd\"\n");
TestSubject = newTB("abcd");
printf("Print text -\n%s\n", dumpTB(TestSubject));
printf("Free text buffer\n");
releaseTB(TestSubject);
printf("Passed\n\n");
}
{
TB TestSubject;
printf("Test 2: Text = \"u\\nda\\nsexay \\nno homo\"\n");
TestSubject = newTB("u\nda\nsexay \nno homo");
printf("Print text - \n%s\n", dumpTB(TestSubject));
printf("Number of lines = %d\n", linesTB(TestSubject));
printf("Free text buffer\n");
releaseTB(TestSubject);
printf("Attempt to find numLines should result in error:\n");
printf("%d\n", linesTB(TestSubject));
printf("Passed\n\n");
}
return;
}
Code:
//textbuffer.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "textbuffer.h"
typedef struct textbuffer *TB;
struct textbuffer {
char *text;
int numLines;
};
/* Allocate a new textbuffer whose contents is initialised with the text given
* in the array.
*/
TB newTB (char text[]) {
TB Buff = malloc(sizeof(struct textbuffer));
assert (Buff != NULL);
int lineCount = 1;
int length = strlen(text);
int i;
for (i=0; i<length; i++) {
if (text[i] == '\n')
lineCount++;
}
Buff->numLines = lineCount;
Buff->text = malloc(sizeof(char)*strlen(text));
strcpy(Buff->text, text);
return Buff;
}
/* Free the memory occupied by the given textbuffer. It is an error to access
* the buffer afterwards.
*/
void releaseTB (TB tb) {
free(tb->text);
free(tb);
}
/* Allocate and return an array containing the text in the given textbuffer.
*/
char *dumpTB (TB tb) {
return tb->text;
}
/* Return the number of lines of the given textbuffer.
*/
int linesTB (TB tb) {
return tb->numLines;
}
With a header file for the function declarations.
My problem is that I can't seem to free the text and struct itself because when I call releaseTB which is supposed to free, I can still access the struct with no problem.