Implementing a stack of "strings" in C - c

I'm trying to implement a stack structure in C, for storing char arrays into.
I have the following code:
typedef struct {
size_t size;
char **data;
} loods1;
loods1 *init(void) {
loods1 *loods = malloc(sizeof(loods1));
loods->data = malloc(sizeof(char *) * STACK_MAX);
for (int i = 0; i < STACK_MAX; i++) {
*(loods->data + i) = malloc(LABEL_LENGTH_MAX * sizeof(char));
}
loods->size = 0;
if (loods == NULL) {
perror("malloc failed\n");
return NULL;
}
return loods;
}
int empty(loods1 *loods) {
return (loods->size == 0);
}
void push(loods1 *loods, char *name) {
if (loods->size == STACK_MAX) {
perror("Stack is full\n");
exit(0);
}
else {
*((loods->data) + loods->size++) = name;
}
}
char *pop(loods1 *loods) {
if (loods->size == 0) {
printf("size == 0\n");
return NULL;
}
else {
printf("%s \n", *(loods->data + 1));
return *(loods->data + (--loods->size));
}
}
int delete(loods1 *loods) {
for (int i = 0; i < STACK_MAX; i++) {
free(*(loods->data + i));
}
free(loods->data);
free(loods);
}
There are 2 problems: first off, every time I add a new element to the stack, it overwrites all existing elements (if '3' and '11' are added and I want to add '15', the new stack will look like '15', '15', '15'). And when I want to pop the stack, the popped value is empty. Not null, but an empty string or something?
I have no idea what I'm doing wrong, but there seems to be a mistake somewhere, obviously.
Sammy

In push function, if you are passing char*, it will divert your pointer to where the char * is, and when you do p++, it will go from the char* you passed.
Try change push definition to:
void push(loods1 *loods, const char *name) {
if (loods->size == STACK_MAX) {
perror("Stack is full\n");
exit(0);
}
else {
strcpy((loods->data)[loods->size++], name);
}
}
From here you might as well need some other changes to your calling program.
Also when you free it, free the single loods does not free all memory you allocated.

I flicked through the code and it seems to be ok, I think the problem is in your client.
Your only store pointers in the stack, you're probably pushing the same pointer on the stack but rewrite the string it points to.
Note that if you really only want to store pointers your 3rd malloc is wasting space and also creates a memory leak.

Related

How to pass array to function and realloc memory in C

I started working on a program and I need to create function, that reads input, in format {number,number, ...} and puts numbers into dynamically allocated array. I am currently having trouble reallocating the array. Here is the code. The program compiles with no errors or warnings
int readInput(int ** znamky, int *count )
{
size_t n = 1;
char overeni[2];
char znaminko[2];
char carka [2] = ",";
char zavorka[2] ="{";
char zavorka2[2] ="}";
printf("Pocty bodu:\n");
scanf(" %c",&overeni[0]); // I check if first character is {
if (overeni[0]!=zavorka[0])
{
printf("Nespravny vstup.\n");
return EXIT_FAILURE;
}
while (scanf("%d",znamky[*count])==1) // here I enter the cycle and load first number
{
if (scanf(" %c",&znaminko[0])==1) // if char after number is ","
{
if (znaminko[0]==carka[0])
{
printf("sdf\n");
*count = *count + 1; // I append lenght of array
if (*count==n) // if the length is same as currently allocated memory
{
n = n*2;
*znamky = (int*) realloc (*znamky, n * sizeof(int) + 4);
// Here I am trying to reallocate the memory and when using debugger it probably goes ok, but //the problem is when I repeat the cycle for the second time because I get seg fault
}
continue;
}
if (znaminko[0]==zavorka2[0])
{
*count = *count + 1;
printf("utikam\n");
return 1;
}
}
else
{
printf("Nespravny vstup\n");
return EXIT_FAILURE;
}
}
return 1;
}
int main (void)
{
int *znamky = (int*) malloc (sizeof(int));
int count = 0;
if (znamky == NULL)
{
free (znamky);
return EXIT_FAILURE;
}
readInput(&znamky, &count);
return 0;
}
So I was wondering if someone could explain to me what is happening inside the program, I still feel a little bit lost with pointers, and passing arrays to functions.
Thank you very much...

Unexpected breakpoint trying to print C string from struct

So I am having two problems with this piece of code. The first problem when I'm following break points through it and I'm trying to copy the array to the struct fields, it is saying Error reading character string. And the second problem I am having is with the output "printMovieInfo function it is not printing out my list and it is causing an "unexpected breakpoint"
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#pragma warning(disable : 4996)
#pragma warning(disable : 6387)
typedef struct {
char* g;
char* t;
}MovieInfo;
#define kTenItemsEntered 10
#define kCharacterString 30
//prototypes
void eliminateEndOfLine(char* buffer);
void getMovieInfo(MovieInfo* ptr, char title[], char genre[]);
void printMovieInfo(MovieInfo list[]);
int main() {
MovieInfo newMovieInfo[kTenItemsEntered];
char title[kCharacterString];
char genre[kCharacterString];
printf("Enter 10 Title of Movie and 10 Genres\n");
for (int i = 1; i <= kTenItemsEntered; i++) {
printf("%d:\n", i);
printf("Title: ");
fgets(title, kCharacterString,stdin);
eliminateEndOfLine(title);
printf("Genre: ");
fgets(genre, kCharacterString, stdin);
eliminateEndOfLine(genre);
getMovieInfo(newMovieInfo, title, genre);
}
printMovieInfo(newMovieInfo);
return 0;
}
void getMovieInfo(MovieInfo* ptr, char title[], char genre[]) {
ptr->t = (char*)malloc(strlen(title) + 1);
if (ptr->t == NULL) {
printf("Error allocating the title in the struct\n");
}
ptr->g = (char*)malloc(strlen(genre) + 1);
if (ptr->g == NULL) {
printf("Error allocating the genre in the struct\n");
}
strcpy(ptr->t, title);
strcpy(ptr->g, genre);
}
void printMovieInfo(MovieInfo list[]) {
printf("%-35s %-35s\n", "Title", "Genre");
for (int i = 0; i < kTenItemsEntered; i++) {
printf("%-35s %-35s\n", list[i].t, list[i].g);
}
}
//This is the end of new line function from examples
void eliminateEndOfLine(char* buffer)
{
char* target = strchr(buffer, '\n');
if (target != NULL)
{
*target = '\0';
}
}
Output
The output does not print
I'm guessing you're actually compiling in C++, otherwise this wouldn't compile as you need to use struct MovieInfo, not MovieInfo in C. You can fix that by doing:
typedef struct MovieInfo {
char* g;
char* t;
} MovieInfo;
In main your newMovieInfo is an array of MovieInfo structs. When you call getMovieInfo(newMovieInfo, title, genre);, you're actually passing a pointer to the first element of the array to the function (the array 'decays' into a pointer to the first element). What you should do instead is pass a pointer to the element you actually want to fill in. Array indices start at 0, not 1, so you need to fix your loop as well:
// previously: for (int i = 1; i <= kTenItemsEntered; i++) {
for (int i = 0; i < kTenItemsEntered; i++) {
...
// previously: getMovieInfo(newMovieInfo, title, genre);
getMovieInfo(&newMovieInfo[i], title, genre);
}
Then in getMovieInfo, since you already have a valid pointer to the struct, you don't need to allocate space for a new one:
void getMovieInfo(MovieInfo* ptr, char title[], char genre[]) {
// removed:
// ptr = (MovieInfo*)malloc(sizeof(MovieInfo));
// if (ptr == NULL) {
// printf("Error allocating the struct\n");
// }
ptr->t = (char*)malloc(strlen(title) + 1);
if (ptr->t == NULL) {
printf("Error allocating the title in the struct\n");
}
ptr->g = (char*)malloc(strlen(genre) + 1);
if (ptr->g == NULL) {
printf("Error allocating the genre in the struct\n");
}
strcpy(ptr->t, title);
strcpy(ptr->g, genre);
}
Finally in printMovieInfo, your current code is printing the first element's data multiple times. You can fix that by indexing into the array to get the element you want:
void printMovieInfo(MovieInfo list[]) {
printf("%-35s %-35s\n", "Title", "Genre");
for (int i = 0; i < kTenItemsEntered; i++) {
// previously: printf("%-35s %-35s\n",list->t,list->g);
printf("%-35s %-35s\n",list[i].t,list[i].g);
}
}
Each time you call getMovieInfo, you're storing the data in a local pointer to allocated memory. That pointer gets lost when the function returns, so newMovieInfo is never populated with anything.
The pointer being passed to the function points to an already existing instance of MovieInfo, so there's no need to allocate memory for it (though you still need to allocate memory for the strings).
Even after this fix, you're only ever updating the first element of the newMovieInfo. You need to pass a pointer to the array element in question when you call getMovieInfo:
getMovieInfo(newMovieInfo + i - 1, title, genre);
Note the -1 here because you're looping from 1 to kTenItemsEntered and array indices in C start at 0. If you changed the loop to go from 0 to kTenItemsEntered-1, you can remove the -1 from the line above.
Your printing function is also only printing the first element of the array, so change the line in the loop body to:
printf("%-35s %-35s\n",list[i].t,list[i].g);

Problem freeing memory from multidimensional array in C, free() crashes program

I am creating a deque to store stings in C, and when I call the free() function, the program crashes. I have implemented a similar structure but only storing integers, and encountered no problems, but this seems to be causing me a few. I created a struct containing a multidimensional array or characters, and i think maybe I am not using the pointers correctly? I have searched far and wide and cannot solve it The main area of concern is when i call clear() from the ain body. That in turn calls free(), and the program just stalls. :-( Any help would be extremely useful.
#include <stdio.h>
#define MAX 20 // number of characters for word
typedef struct {
char **deque;
int size;
int pFront;
int pRear;
} deque;
typedef int bool;
enum { false, true };
void initDeque(deque *d, int initialSize)
{
d->size = initialSize;
d->pFront = -1;
d->pRear = -1;
d->deque = (char **)malloc(sizeof(char*)*initialSize);
int idx;
for(int idx = 0; idx < d->size; idx++)
{
d->deque[idx] = (char *)malloc((MAX+1) * sizeof(char));
d->deque[idx] = "";
}
printf("d->size: %zu\n", d->size);
}
void clear(deque *d) {
if(d->pFront == -1)
{
printf("Queue is empty\n");
}
else
{
printf("Attempting to clear...\n");
for(int idx = 0; idx < d->size; idx++)
{
printf("Attempting to clear columns...");
free(d->deque[idx]);
}
printf("Attempting to clear rows...");
free(d->deque);
printf("Freed!!!!\n");
d->deque = NULL;
d->size = 0;
d->pFront = -1;
d->pRear = -1;
}
}
bool isEmpty(deque *d)
{
if(d->pFront == -1){
return true;
}
else
{
return false;
}
}
bool isFull(deque *d)
{
if(d->size == d->pRear+1)
{
return true;
}
else
{
return false;
}
}
void display(deque *d)
{
if(isEmpty(d)){
printf("empty\n");
}
else{
printf("Deque Values:\n");
int idx;
for(int idx = 0; idx <= d->pRear; idx++)
{
printf("Index: %zu\tValue: %s\n", idx, d->deque[idx]);
}
printf("Size: %zu\n", d->size);
}
}
void rAppend(deque *d, char item[]) // as in rear append - same enqueue for queue structure.
{
if(isFull(d))
{
printf("Is Full\n");
int idx;
deque dTemp;
initDeque(&dTemp, d->size);
printf("dTemp Initialised\n");
for(idx = 0; idx < d->size; idx++)
{
dTemp.deque[idx] = d->deque[idx];
}
printf("deque copied to dTemp:\n");
for(idx = 0; idx < d->size; idx++)
{
printf("dTemp[%zu]: %s\n", idx, dTemp.deque[idx]);
}
clear(&d);
printf("d cleared\n");
initDeque(&d, dTemp.size*2);
printf("New deque of double length initialised\n");
for(idx = 0; idx < dTemp.size; idx++)
{
d->deque[idx] = d->deque[idx];
}
printf("dTemp Copied to new deque\n");
clear(&dTemp);
printf("dTemp Cleared\n");
char **tmp = realloc( d->deque, sizeof (d->deque) * (d->size*2) );
if (tmp)
{
d->deque = tmp;
for (int i = 0; i < d->size; i++)
{
d->deque[d->size + i] = malloc( sizeof(char) * MAX );
}
}
}
printf("Appending to rear.. %s\n", item);
d->pRear++;
d->deque[d->pRear] = item;
if(d->pFront == -1)
d->pFront = 0;
}
int main(void)
{
deque d;
initDeque(&d, 5);
rAppend(&d, "when");
rAppend(&d, "will");
rAppend(&d, "wendy");
rAppend(&d, "walk");
rAppend(&d, "with");
display(&d);
clear(&d);
return 0;
}
The problem is your are calling free() on static chain "when", "will",...
You can replace insertion in the function void rAppend(deque *d, char item[]) :
d->deque[d->pRear] = item;
with:
d->deque[d->pRear] = strdup(item);
Doing like this chains are allocated in the heap and free from the heap.
After there is others problems in the code, but it run without crash.
The main problem seems to be that you don't appreciate the difference between copying / assigning pointers and copying / assigning the data to which they point. Secondarily, it seems you may not appreciate the utility of pointers that don't point to anything, especially null pointers. Some details follow.
You are dynamically allocating space for a bunch of strings ...
for(int idx = 0; idx < d->size; idx++)
{
d->deque[idx] = (char *)malloc((MAX+1) * sizeof(char));
... and then leaking all of that space by replacing the pointer to each with a pointer to an empty string literal:
d->deque[idx] = "";
}
As if the leak were not bad enough, you are not permitted to free a string literal or modify its content, which you nevertheless try to do to any of those pointers that remain in the dequeue whenever you clear() it. This is likely the cause of some of your errors.
If you want to set each allocated string to an empty one then modify its content instead of replacing the pointer to it. For example:
d->deque[idx][0] = '\0';
In fact, however, you probably don't need to do even that. You are already performing bookkeeping to know which arrays contain valid (string) data and which don't, and that should be sufficient to do the right thing. Supposing you maintain copies of the strings in the first place.
But that's not all. When you rAppend() elements to your deque you have a similar problem. You create a temporary deque, and then copy the string pointers from your original deque into the temporary:
dTemp.deque[idx] = d->deque[idx];
Not only does this leak the original (empty) data in the temporary deque, it aliases that deque's contents with the main deque's. When you later clear the temporary deque, therefore, you free all the string pointers in the original. Subsequently using or freeing them produces undefined behavior.
Perhaps you instead want to strcpy() all the elements of the main deque into the temp and back, but I suggest instead skipping the temp deque altogether with something along these lines:
void rAppend(deque *d, char item[]) // as in rear append - same enqueue for queue structure.
{
if(isFull(d))
{
printf("Is Full\n");
char **tmp = realloc(d.deque, d->size * 2);
if (tmp)
{
d->deque = tmp;
for (int i = 0; i < d->size; i++)
{
// Copied from the original, but see below
d->deque[d->size + i] = malloc( sizeof(char) * MAX );
}
d->size * 2;
} // else?
}
printf("Appending to rear.. %s\n", item);
d->pRear++;
// Oops, this is another leak / aliasing issue:
d->deque[d->pRear] = item;
if(d->pFront == -1)
d->pFront = 0;
}
The whole point of the temporary deque is lost on me, since the realloc() you need to do preserves the original data anyway (as long as it succeeds, anyway).
Note too, however, that this still has an aliasing issue: you have aliased a deque element with the appended string, and leaked the memory allocated for that element. Furthermore, when you clear the deque, you free that string for everyone holding a pointer to it. Or at least you attempt to do so. You're not permitted to do that to string literals.
I suggest not allocating space in your deque for the individual strings at all, and not freeing it. Continue to use assignment to store elements in your deque, understanding and embracing that these are aliases. This will be more analogous to your implementation for ints.
#include<memory>
#include<iostream>
using namespace std;
struct S {
S() { cout << "make an S\n"; }
~S() { cout << "destroy an S\n"; }
S(const S&) { cout << "copy initialize an S\n"; }
S& operator=(const S&) { cout << "copy assign an S\n"; }
};
S* f()
{
return new S; // who is responsible for deleting this S?
};
unique_ptr<S> g()
{
return make_unique<S>(); // explicitly transfer responsibility for deleting this S
}
int main()
{
cout << "start main\n";
S* p = f();
cout << "after f() before g()\n";
// S* q = g(); // this error would be caught by the compiler
unique_ptr<S> q = g();
cout << "exit main\n";
// leaks *p
// implicitly deletes *q
}

using functions in c (return value)

Learning C and having many doubts.
I have a function (lets say function 1) that calls another function (lets say function 2).
Function 2 calculates an array of string.
How can I use this array in function 1?
Some code example:
int find_errors(char* word)
{
char error[100];
/*Given the word, It will find the duplicate chars and store it in the
error array. */
return 0;
}
int find_word(char* word)
{
find_errors (word);
printf("%s\n", error);
return 0;
}
There are at least three possible approaches:
Use a global variable
pass a parameter between them
return a pointer from the function
There are multiple ways to do this.
1) Create a dynamic array and return a pointer to the array. This will require you to manually free the memory for the array at a later time.
#define NUM_ELEMS 50
// In find_error():
char* error = malloc(NUM_ELEMS * sizeof(char));
return error;
// In find_word():
char *error = find_errors();
// do stuff
free(error);
2) Pass a pointer to find_errors that it can use as the error array. This will not require you to manually free the memory.
// In find_word():
char error[NUM_ELEMS];
find_error(error);
3) Use a global array. May make it more difficult for other people to understand your code. Has other potential problems as well.
// In global scope:
char error[NUM_ELEMS];
Your question relates to "call-by-reference" and "call-by-value".
char* getNewValsToSet(void)
{
char* new_vals = (char*) malloc(sizeof(char[5]));
new_vals[4] = '\0';
return new_vals;
}
void setValuesEven(char* vals_to_set)
{
vals_to_set[0] = 'A';
vals_to_set[2] = 'C';
}
void setValuesOdd(char* vals_to_set)
{
vals_to_set[1] = 'B';
vals_to_set[3] = 'D';
}
int main(void)
{
char* some_vals_to_set = getNewValsToSet();
setValsEven(some_vals_to_set);
setValsOdd(some_vals_to_set);
// ... now has vals "ABCD"
free(some_vals_to_set); //cleanup
return 0;
}
If you have "doubts" about learning C, IMHO it's one of the best things you can do (no matter the language in which you work) because it will explain exactly how things work "under-the-hood" (which all high-level languages try to hide to some degree).
You need to declare the error array globally and use it just like you did.
EDIT: using global variables isn't the best practice in most of the cases, like this one.
Here is an example of what you are looking for with an awesome console output. It dynamically allocates the array to hold any number errors (duplicate characters in your case) that may occur.
//Only free errors if result is > 0
int find_errors(char* word, char** errors)
{
int num_errors = 0;
int word_length = strlen(word);
int ARRAY_SIZE = MIN(8, word_length);
char existing[word_length];
int existing_index = 0;
*errors = NULL;
for(int i = 0; i < word_length; i++)
{
char character = word[i];
//Search array
for (int n = 0; n < word_length; ++n ) {
if(n >= existing_index)
{
existing[n] = character;
existing_index++;
break;
}
if (existing[n] == character) {
num_errors++;
if(!*errors)
*errors = (char*)malloc(ARRAY_SIZE * sizeof(char));
//Check if we need to resize array
if(num_errors >= ARRAY_SIZE)
{
ARRAY_SIZE *= 2;
ARRAY_SIZE = MIN(ARRAY_SIZE, word_length);
char *tmp = (char*)malloc(ARRAY_SIZE * sizeof(char));
memcpy(tmp, *errors, (unsigned long)ARRAY_SIZE);
free(*errors);
*errors = tmp;
}
//Set the error character
(*errors)[num_errors - 1] = character;
break;
}
}
}
return num_errors;
}
int find_word(char* word)
{
char* errors;
int errCount = find_errors (word, &errors);
if(errCount > 0)
{
printf("Invalid Characters: ");
for(int i =0; i < errCount; i++)
{
printf("%c ", errors[i]);
}
printf("\n");
free(errors);
}
return 0;
}
int main(int argc, char *argv[])
{
find_word("YWPEIT");
find_word("Hello World");
find_word("XxxxXXxXXoooooooOOOOOOOOOOOOOOOooooooooOOOOOOOOOOOOooooooOOO");
}

glibc detected - double free or corruption

this might be a bit long so my apologies.
consider the following code (i've left some irrelevant parts from it). this code receives a pointer to a struct (BoardP theBoard), x & y coords and a value.
the goal is to place the value in a 2D array that is found in the struct.
if the coords are out of bounds, i have to increase the size of the table, copy old data to new data and place the value in its place.
well this code works the first call but in the second call it crashes and writes:
*** glibc detected *** ./b: double free or corruption (top): 0x092ae138 ***
i couldn't find an answer to it and i hope you will help.
These are the calls from main()
BoardP p = CreateNewBoard(10,10);
PutBoardSquare(p,10,5,'X');
PutBoardSquare(p,5,10,'O');
Boolean PutBoardSquare(BoardP theBoard, int X, int Y, char val) {
if (inBounds(X,Y,theBoard->_rows,theBoard->_cols)) {
theBoard->_board[X * theBoard->_cols + Y] = val;
return TRUE;
}
else {
int newRows = (X>=theBoard->_rows) ? (2*X) : theBoard->_rows;
int newCols = (Y>=theBoard->_cols) ? (2*Y) : theBoard->_cols;
BoardP newBoard = CreateNewBoard(newCols,newRows); //this creates a new Board with the new dimensions
if (newBoard == NULL) {
//ReportError(MEM_OUT);
return FALSE;
}
else {
copyData(theBoard,newBoard);
freeBoardArray(&theBoard->_board[0]); //free old array
theBoard->_board = newBoard->_board; //old array point to new array
FreeBoard(newBoard); //free the temp copy THIS CAUSES THE PROBLEM
PutBoardSquare(theBoard,X,Y,val);//recursion, will be in bounds now
return TRUE;
}
}
}
These are the Free functions:
void FreeBoard(BoardP board) {
if (board != NULL) {
printf("FREE 1\n");
//free the board array:
if (board->_board != NULL) {
printf("FREE 2\n");
freeBoardArray(&board->_board[0]);
printf("FREE 3\n");
}
free(board);
}
}
static void freeBoardArray(char * arrP) {
free(arrP); //**PROGRAM CRASH HERE**
}
This is how i create a new board:
BoardP CreateNewBoard(int width, int high) {
BoardP board = (BoardP) malloc(sizeof(Board));
if (board != NULL) {
board->_board = allocateBoardArray(high,width);
if ( board->_board == NULL) {
FreeBoard(board);
//TODO make file ReportError(MEM_OUT);
return NULL;
}
initializeBoard(board,high,width,X_SIGN,SPACE);
return board;
}
else {
FreeBoard(board);
//TODO make file ReportError(MEM_OUT);
return NULL;
}
}
static char* allocateBoardArray(int row, int col) {
char* newBoard = (char*) malloc(row * col * sizeof(char));
if (newBoard == NULL) {
return NULL;
}
return newBoard;
}
this is BoardP:
typedef struct Board* BoardP;
You have to free memory which you have allocated and no longer want to hold a reference too.
from your code i can see the following line.
theBoard->_board = newBoard->_board;
Now you maintain reference to a allocated pointer and then free that same pointer itself.
Example code:
char *foo()
{
char *ref1;
char *ref2;
ref1 = malloc(256);
ref2=ref1;// Holding reference to a pointer in another pointer
strcpy(ref1,"stackoverflow");
printf("%s %s",ref1,ref2); // This prints stackoverflow twice
free(ref1); // This is valid but you can access ref2 or ref1 after this point
return ref2; /// This will cause problems
}
Try this:
copyData(theBoard, newBoard);
/* swap the _board pointers */
char * b = theBoard->_board;
theBoard->_board = newBoard->_board;
newBoard->_board = b;
FreeBoard(newBoard); /* cleanup the temp struct and the old array */
This errors says that you are trying to free the memory which is already freed by you. What i am suspecting here is this block of code
if (board != NULL) {
printf("FREE 1\n");
//free the board array:
if (board->_board != NULL) {
printf("FREE 2\n");
freeBoardArray(&board->_board[0]);
printf("FREE 3\n");
}
free(board);
once you are freeing the part of structure freeBoardArray(&board->_board[0]); and then you are freeing the whole structure free(board);, and it looks to me causing the problem.Why you passing the address of the _board pointer?I wrote the code on the same line of code,which causing the problem.
struct a{
int * next;
};
int main(){
struct a *aptr = (struct a *)malloc(sizeof(struct a));
aptr->next=(int *)malloc(5*sizeof(int));
free(&aptr->next);
free(aptr);
return 0;
}
this code will cause the same issue as you shown. Now again try this code after removing '&' from free(&aptr->next);statement.It will work fine.
So i think you got a clue where you have to modify.
Running this code under valgrind will tell you exactly on which line you a.) first freed the memory and b.) when you tried to free it again.
It will also tell you if you try and access any addresses which are inside a block that you have freed.

Resources