Reputation: 2141
Following is the code for a simple malloc
implementation. A linked list is initiated with a head and tail pointer for memory management. Now in the function, there is only a single call implemented when the list is uninitialized, where the list's head is initialized. Once I return the underlying pointer to main
, the program gives segmentation fault
. On the other hand, the following test
function with almost the same parameters except for the complicated handling of linked list computes correctly and displays the result. Can anyone please tell what am I missing here?
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <sys/types.h>
typedef struct Items{
size_t size_of_object;
size_t free;
} Items;
typedef struct Node{
void *ptr;
void *next;
Items Item;
}Node ;
typedef struct LinkedList{
Node *head;
Node *tail;
} LinkedList;
LinkedList memory_list;
void *salmalloc(size_t size_of_object) {
if (memory_list.head == NULL) {
memory_list.head = sbrk(sizeof(Node));
memory_list.head->ptr = sbrk(size_of_object);
memory_list.head->Item.size_of_object = size_of_object;
memory_list.tail = NULL;
memory_list.head->next = NULL;
memory_list.head->Item.free = 1;
return memory_list.head->ptr;
}
}
void *test(size_t size) {
void *p = sbrk(size);
return p;
}
void main(){
char *p = NULL;
char a = 'B';
p = salmalloc(sizeof(char));
*p = a;
printf("%c\n", *p);
}
Upvotes: 0
Views: 575
Reputation: 92306
I see a few issues:
memory_list
.salmalloc
is missing an else
part and since there is no return
it will return random garbage in this case.sbrk
, it may fail (but salmalloc
looks like work-in-progress anyway, isn't it?).salmalloc
, it may fail.Here's a version that works on my system:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <sys/types.h>
typedef struct Items{
size_t size_of_object;
size_t free;
} Items;
typedef struct Node{
void *ptr;
void *next;
Items Item;
}Node ;
typedef struct LinkedList{
Node *head;
Node *tail;
} LinkedList;
LinkedList memory_list = { 0 };
void *salmalloc(size_t size_of_object) {
if (memory_list.head == NULL) {
memory_list.head = sbrk(sizeof(Node));
memory_list.head->ptr = sbrk(size_of_object);
memory_list.head->Item.size_of_object = size_of_object;
memory_list.tail = NULL;
memory_list.head->next = NULL;
memory_list.head->Item.free = 1;
return memory_list.head->ptr;
} else {
return NULL;
}
}
int main(){
char *p = NULL;
char a = 'B';
p = salmalloc(sizeof(char));
if (p == NULL) {
printf("Allocation failed.\n");
return 1;
}
*p = a;
printf("%c\n", *p);
return 0;
}
Upvotes: 1