I am creating source files containing buffer functions that I want to use for my other library that I am creating.
It works correctly, but it's hard for me to get rid of the buffer structure that I create in one of the functions. The following snippets should help illustrate my problem:
Header C:
...
typedef struct{
char *pStorage;
int *pPosition;
int next_position;
int number_of_strings;
int total_size;
}DBUFF;
...
Source C:
...
DBUFF* dbuffer_init(char *init_pArray)
{
int size = sizeof_pArray(init_pArray);
DBUFF *buffer = malloc(sizeof(DBUFF));
buffer->pStorage = malloc( (sizeof(char)) * (size) );
strncpy( &(buffer->pStorage)[0] , &init_pArray[0] , size);
buffer->number_of_strings = 1;
buffer->total_size = size;
buffer->next_position = size;
buffer->pPosition = malloc(sizeof(int) * buffer->number_of_strings );
*(buffer->pPosition + (buffer->number_of_strings -1) ) = 0;
return buffer;
}
void dbuffer_destroy(DBUFF *buffer)
{
free(buffer->pStorage);
free(buffer);
}
...
Home:
#include <stdio.h>
#include <stdlib.h>
#include "dbuffer.h"
int main(int argc, char** argv)
{
DBUFF *buff;
buff = dbuffer_init("Bring the action");
dbuffer_add(buff, "Bring the apostles");
printf("BUFFER CONTENTS: ");
dbuffer_print(buff);
dbuffer_destroy(buff);
printf("%s\n", buff->pStorage);
printf("buff total size: %d\n", buff->total_size);
return (EXIT_SUCCESS);
}
Exit:
BUFFER CONTENTS: Bring the action/0Bring the apostles/0
/
buff total size: 36
RUN SUCCESSFUL (total time: 94ms)
Question:
Why can I still access the contents of the structure using the next line after the pointer to the structure has been freed?
printf("buff total size: %d\n", buff->total_size);
source
share