i have a problem inside my program, i've implemented a simple stack in C
the problem is that when i try to reallocate the stack array for the second time, the program triggers a brekapoint just inside the realloc function, i don't know what could be wrong since i'm using a buffer to check whether realloc fails or not. probably, this code is where i use the realloc function:
struct stack {
void** data;
int top;
int initial_size;
};
static void stack_resize(struct stack* instance, int capacity)
{
if (instance->initial_size == instance->top)
{
int new_sz = capacity * sizeof *instance->data;
// THIS REALLOC crashes
void** buffer = realloc(instance->data, new_sz); // realloc the stack array
printf("reallocating memory\n");
if (buffer) {
instance->data = buffer;
instance->initial_size = new_sz;
}
}
}
the following function instead, is where the stack_resize() gets called
void stack_push(struct stack* instance, void* data)
{
if (instance->top >= instance->initial_size)
{
// shrink the array
stack_resize(instance, instance->initial_size);
}
instance->data[++instance->top] = data;
printf("pushing onto the stack!\n");
}
This is the constructor where i initialize all the data.
struct stack* stack_new(int initial_size)
{
struct stack* new_stack = (struct stack*)malloc(sizeof(struct stack));
if (!new_stack) {
fprintf(stderr, "no memory available from the operative system\n");
return NULL;
}
memset(new_stack, 0, sizeof(struct stack));
new_stack->data = (void**)malloc(sizeof(void*) * initial_size);
if (!new_stack->data) {
fprintf(stderr, "could not allocate memory for the buffer\n");
return NULL;
}
printf("created a stack with %d slot(s)\n", initial_size);
new_stack->top = -1;
new_stack->initial_size = initial_size;
return new_stack;
}
and this is the entry point of the program:
int main(int argc, char** argv)
{
struct stack* new_stack = stack_new(2);
for (int i = 0; i < 55; i++)
{
stack_push(new_stack, (void*)i);
}
getchar();
return 0;
}
Any help would be much appreciated! thanks to all.
Crash is seen because you are assigning new_sz to instance->initial_size.
since new_sz holds actual size of array in bytes, which is capacity*sizeof(void *)
int new_sz = capacity * sizeof *instance->data;
instance->initial_size = new_sz;
your stack top and initial_size will mismatch.
if (instance->top >= instance->initial_size)
Your top will always less then initial_size and you will not allocate new memory.
In order to your program to work you need to make the following changes.
int new_sz = (capacity+1) * sizeof(void *);
instance->initial_size = capacity+1;//instead of new_size
Related
I'm trying to implement stack in C.
What I'm going for:
Design a Stack structure with push and pop functions for the implementation.
Create a Memory structure owns number of block, block size, and stack attributes.
Stack attribute represents memory blocks. Number of block attribute represents the length of the stack. Block size represents the maximum value that each element in the stack can get.
Write an allocate function that takes a size parameter. If the given size is bigger than block size of the Memory, the allocation will be distributed to the different blocks in the stack attribute.
For example, calling allocate(27) updates the stack as:
allocate(27) = [10, 10, 7, 0, 0]
for a Memory with number of block = 5, block size = 10. The remaining of the elements which don't have maximum value can be sealed until the element is flushed. Therefore, the next allocation can start from next element position after 7 given above.
Write a deallocate function that flushes the last used block.
My Work:
First, created the structs:
stack attribute represents memory blocks.
number of block attribute represents the length of the stack.
Block size represents the maximum value that each element in the stack can get.
#include <stdio.h>
#include <stdlib.h> // Provides function For memory locating. allocate & deallocate.
struct Stack {
int top;
};
struct Memory{
int stack;
int number_of_block; // 5
int block_size; // 10
};
Then I have tried to create allocate & push function but they are not working.
int main(){
allocate(30);
return 0;
}
int allocate(int size){
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
struct Memory* memory = (struct Memory*)malloc(sizeof(struct Memory));
memory->block_size = 10;
stack->top = -1;
memory->stack = (int*)malloc(memory->block_size * sizeof(int));
struct Memory memory = {1, 5, 10};
for(int i = 0; i < 5; i++){
if(size > 10){
size = size - 10; //27 - 10 = 17 -> 17 - 10 = 7
push(stack, 10);
}
}
if(size % 10 != 0){
int size_mod = size % 10; //27 % 10 = 7
push(stack, size_mod);
}
}
void push(struct Stack* stack, struct Memory* memory, int item){
if(stack->top == memory->block_size - 1){
return;
}
memory->stack[++stack->top] = item;
printf("%d ", item);
}
The Memory structure contains a pointer to the first block, as well as the number of blocks and the maximum size of each block. Each block then contains the data and a pointer to the next block, meaning all the blocks are stored in a linked list.
The function allocate returns a pointer to the Memory structure created.
#include <stdio.h>
#include <stdlib.h>
struct Block {
int data;
struct Block *next;
};
struct Memory {
int block_count;
int block_size;
struct Block *head;
};
/* Push a new block onto the stack */
void push(struct Block **head, int data)
{
struct Block *new = malloc(sizeof *new);
if (!new) {
printf("Error: memory allocation failed");
exit(EXIT_FAILURE);
}
new->data = data;
*head = new;
/* `printf` is not needed */
printf("%d\n", data);
}
/* Returns a pointer to the `Memory` structure */
struct Memory *allocate(int size)
{
struct Memory *memory = malloc(sizeof *memory);
if (!memory) {
printf("Error: memory allocation failed");
exit(EXIT_FAILURE);
}
memory->block_count = 5;
memory->block_size = 10;
struct Block *head = NULL;
for (int i = 0; i < memory->block_count; ++i) {
int data = 0;
if (size > 10)
data = 10;
else if (size > 0)
data = size;
size -= data;
push(&head, data);
}
memory->head = head;
return memory;
}
int main(void)
{
struct Memory *memory = allocate(27);
return EXIT_SUCCESS;
}
And as you can see, you don't need to cast malloc, because it returns void *, which is automatically and safely promoted to any other pointer.
I have a program that creates a struct named Stack that holds a pointer to an array of ints and an int that shows the size of this array.
I have functions to:
Initialize the struct with empty values
Push integers to the array (dynamically allocate more memory and write a value to it)
Pop an int from the array
However, when I try to pop the last element by freeing the memory it occupies, my program crashes.
What am I doing wrong here?
Is my process correct?
I realize the problem is probably that I'm trying to free a segment of memory that has not been allocated dynamically, but I just don't see where the issue is exactly.
#include <stdio.h>
#include <stdlib.h>
#include <mem.h>
struct Stack{
int *array;
int size;
};
typedef struct Stack Stack;
void initStack(Stack *stack);
void push(Stack *stack, int value);
int pop(Stack *stack);
int main()
{
Stack firstStack;
initStack(&firstStack);
push(&firstStack, 1222);
pop(&firstStack);
push(&firstStack, 555);
for(int i = 0; i < firstStack.size; ++i){
printf("#%d: %d (%p) ", i , firstStack.array[i], &firstStack.array[i]);
}
return 0;
}
void initStack(Stack *stack){
stack->array = NULL;
stack->size = 0;
}
void push(Stack *stack, int value){
int size = stack->size;
int newSize = size + 1;
stack->array = realloc(stack->array, newSize * sizeof(int));
if(stack->array != NULL){
stack->array[size] = value;
stack->size = stack->size + 1;
}
else{
printf("MALLOC ERROR");
}
}
int pop(Stack *stack){
int lastValue = stack->array[stack->size];
int lastIndex = (stack->size)-1;
int* lastAddress = (stack->array)+lastIndex;
free(lastAddress);
stack->size = (stack->size) - 1 ;
printf("memory free\n");
return lastValue;
}
int* lastAddress = (stack->array)+lastIndex;
free(lastAddress);
is wrong because lastAddress may not be an address allocated via malloc() family by adding lastIndex.
Remove the line
free(lastAddress);
If you want the system to change tha allocated size, you should change the line to
stack->array = realloc(stack->array, ((stack->size) - 1) * sizeof(int));
This is a problem:
int* lastAddress = (stack->array)+lastIndex;
free(lastAddress);
The argument to free must be an address value returned from malloc, calloc, or realloc - you cannot free memory at an arbitrary address, even within a dynamically allocated block.
Can we dynamically allocate memory for structures? Is this a correct procedure to approach a dynamically allocated structures? Please tell me how to malloc() and realloc() a structure.
newnode is of type struct List * but when start indexing it converts to struct List.How this conversion possible?My insert function accepts only (struct List*) Am I wrong somewhere?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct List {
char val[20];
};
void insert(struct List *);
int main(void) {
int i = 0;
int size = 1;
struct List *newnode = (struct List *)malloc(size * sizeof(struct List));
for (i = 0; i < 5; i++) {
if (size <= i) {
size = size + size;
newnode = (struct List *)realloc(newnode, size * sizeof(struct List));
}
scanf("%s", newnode[i].val);
insert(newnode[i]);
}
for (i = 0; i < 5; i++) {
printf("%s\n", newnode[i].val);
}
return 0;
}
void insert(struct List *node) {
printf("%s\n", node->val);
}
The code works except for 3 problems:
You do not test for memory allocation failure. Both malloc() and realloc() will return NULL if memory cannot be allocated: you will get undefined behavior when dereferencing newnode should this happen.
to handle the case of realloc() failure gracefully, you should store the reallocated pointer to a different variable so you can still access the previous array that has not been deallocated and free it.
scanf("%s", newnode[i].val); is a security flaw: you should limit the number of bytes that can be stored to the destination array with
scanf("%19s", newnode[i].val);
you do not test the return value of scanf() to detect invalid or missing input.
insert() does not insert anything.
Here is a modified version with error handling and less confusing names:
#include <stdio.h>
#include <stdlib.h>
struct Item {
char val[20];
};
//void insert(struct Item *);
int main(void) {
int i, j;
int size = 0;
struct Item *array = NULL;
for (i = 0; i < 5; i++) {
if (i >= size) {
int newsize = size ? 1 : size + size;
struct Item *newarray = realloc(array, sizeof(*array) * size);
if (newarray == NULL) {
perror("cannot reallocate the array");
break;
}
size = newsize;
array = newarray;
}
if (scanf("%19s", array[i].val) != 1) {
fprintf(stderr, "missing input\n");
break;
}
//insert(array[i]);
}
for (j = 0; j < i; i++) {
printf("%s\n", array[i].val);
}
free(array);
return 0;
}
Yes, this is fine except that you are assigning the return value to your original array pointer. realloc() returns NULL if it can't resize the memory. You need to assign it to a temporary variable and, if the value is NULL, don't overwrite a.
The main thing you have to watch out for are pointers, which your struct doesn't have. In those cases, the memory pointed to is not part of the allocated array.
I have been assigned to program a generic stack in ANSI C. It is meant to be for primitive datatypes. Until here there was no big problem whatsoever.
Afterwards I was asked to reprogram my application so that even complex data types can be used on my stack. I have searched and researched for the last week and I found nothing that could be helpful enough.
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stddef.h>
#include "genstacklib.h"
void (*freefn) (void*);
/*
* ToDo
*/
void GenStackNew(genStack *s, int elemSize, void (*freefunk) (void*))
{
s->elems = malloc (elemSize * GenStackInitialAllocationSize);
freefn = freefunk;
assert (s->elems != NULL);
s->elemSize = elemSize;
s->logLength = 0;
s->allocLength = GenStackInitialAllocationSize;
}
/*
* ULStackPush adds an element to the stack and allocates new memory if
* needed. If there is not enough memory, ULStackPush does nothing.
*/
void GenStackPush (genStack *s, const void *elemAddr)
{
/*assert (sizeof(*elemAddr) == s->elemSize);*/
assert (s->elems != NULL);
if (s->logLength == s->allocLength)
{
void *temp = NULL;
temp = realloc (s->elems, 2 * s->allocLength * s->elemSize);
assert (temp != NULL);
s->allocLength = 2 * s->allocLength;
s->elems = temp;
}
memcpy(currentval(s), elemAddr, s->elemSize);
s->logLength = s->logLength + 1;
}
void GenStackPop (genStack *s, const void *elemAddr)
{
assert (s->elems != NULL);
assert (s->logLength != 0);
(s->logLength)--;
memcpy((void *)elemAddr, currentval(s), s->elemSize);
}
void *currentval(genStack *s)
{
assert (s->elems != NULL);
return ((size_t*)s->elems + s->logLength * s->elemSize);
}
bool GenStackEmpty (const genStack *s)
{
assert (s->elems != NULL);
return s->logLength == 0;
}
void GenStackDispose (genStack *s)
{
assert (s->elems != NULL);
s->logLength = 0;
free (s->elems);
freefn();
}
/*
* ToDO
*/
void *freefn (void *) {
free
And my header data is:
#ifndef GENSTACKLIB_H
#define GENSTACKLIB_H
#include <stdbool.h>
#define GenStackInitialAllocationSize 4
typedef struct
{
void *elems;
int elemSize;
int logLength;
int allocLength;
} genStack;
void GenStackNew (genStack * s, int elemSize);
bool GenStackEmpty (const genStack * s);
void GenStackPush (genStack * s, const void *elemAddr);
void GenStackPop (genStack * s, const void *elemAddr);
void GenStackDispose (genStack * s);
void *currentval(genStack *s);
#endif
In the first block of code, I believe that what has to be done is in the ToDo markings.
How can I make it to use my stack for complex data types?
Thanks in advance
I dont see any problem with "complex" types like strings... there is no real difference bewteen pointer to string and pointer to int. So just store pointers (or pointers to pointers) and that should work.
So instead of element to be "int".. element is pointer to pointer.
Basic idea in form of very "pseudo" C code
typedef struct Wrapper
{
void * primitiveData;
} Wrapper;
void PrimitivePush(void * data)
{
Wrapper * w = malloc();
w->primitiveData = malloc();
memcpy(w->primitiveData, data);
ClassicComplexTypePush(&w)
}
ClassicComplexTypePush(void ** data)
{
push data to stack
}
Consider using a singularly linked list for implementation, since when
using a stack, we don't know how many items may be needed.
Use a byte* or (char*) to store the contents of memory, instead of a void* (which would also work, but we may need to pad the allocation, to include structs)
Copy memory into a new allocation, which is pushed onto the stack,
then delete that used upon pop.
each node has to be of the same type, or at-least the same size,
errors using wrong type though may be undesired
pop can be either used to check if the stack is empty by passing (NULL)
or to actually pop the stack, by referencing the memory you want to set.
typedef unsigned char byte;
Create the structures which will be used to keep track of the stack
struct gStackNode {
byte *data;
struct gStackNode *next;
};
struct gStack {
unsigned size;
struct gStackNode *head;
};
Initialize the stack, including the size of the type we will be using
void stack_initalize(struct gStack *stk, unsigned size) {
if (!stk)
return;
stk->size = size;
stk->head = (void*)0;
}
Always, we need to manually free the stack, in-case not all were popped
void stack_free(struct gStack *stk) {
if (!stk)
return;
struct gStackNode *temp;
/* step through the remaining stack, deleting each item */
while(stk->head) {
temp = stk->head->next;
free((byte*)stk->head->data);
free((struct gStackNode *)stk->head);
stk->head = temp;
}
}
push an item onto the stack
void stack_push(struct gStack *stk, void *data) {
struct gStackNode *node = (struct gStackNode*)malloc(sizeof(struct gStackNode));
struct gStackNode *temp = stk->head;
node->next = temp;
node->data = (byte*)malloc(sizeof(byte)*(stk->size));
byte * src = (char*)(data);
byte * dest = (char*)(node->data);
unsigned n = stk->size;
/* fill the new allocation with source data */
for(;n;n--)
*(dest++) = *(src++);
/* the node becomes the new head */
stk->head = node;
}
Sometimes we don't want to use a local variable ie: stack_pop_(stack, &type) we can use stack_push_arg_no_ref(stack, 10).
void stack_push_arg_no_ref(struct gStack *stk, void *data) {
stack_push(stk, &data);
}
Now we can pop, and use the same to peek, passing (NULL) to data will result in a peek,
returning (1) if there is an item in the stack, and a (0) if its empty
int stack_pop(struct gStack *stk, void * data) {
if (!stk)
return 0;
if (!stk->head)
return 0;
if (data == (void*)0) {
/*
simply check to see if the stack is empty or not
don't actually pop the stack
*/
return ((!stk->head == (void*)0));
} else {
struct gStackNode *next = stk->head->next;
struct gStackNode *node = stk->head;
unsigned i;
byte *c_temp = (byte*)data;
for(i=0;i<stk->size;i++)
*c_temp++ = node->data[i];
free((byte*)node->data);
free((struct gStackNode*)node);
stk->head = next;
}
}
Finally we can implement the stack
using any ANSI C data types
the size of a character string needs to be fixed
structs can also be used
Using a character string
CAUTION, for this example, the strings need to be NULL terminated, though
it is possible to use non-NULL terminated strings
char ta[32] = "ta: text 1";
char tb[32] = "tb: text 2";
char tc[32];
struct gStack stack_char; stack_initalize(&stack_char, sizeof(ta));
stack_push(&stack_char, ta);
stack_push(&stack_char, tb);
while (stack_pop(&stack_char, &tc))
printf("%s\n", tc);
be sure to free the stack
stack_free(&stack_char);
Using integers
int a = 120, b = -32, c;
struct gStack stack_int; stack_initalize(&stack_int, sizeof(int));
stack_push(&stack_int, &a);
stack_push(&stack_int, &b);
/* or we can use */
stack_push_arg_no_ref(&stack_int, 1776);
/* we can now see the contents of the stack */
while (stack_pop(&stack_int, &c))
printf("%d\n", c);
stack_free(&stack_int);
when I'm trying to push elements to a stack I get segmentation fault, but if I open address for stack(i marked them with "!!!") and it's symbols it accepts it. But this time in each push, it creates new address and doesn't increase top value.
typedef struct
{
struct table **symbols; // array of the stack
int top; //index of the top element
int size; //maximum size of the stack
}stack;
void push(stack *stck,struct table *element)
{
if(stck->top == stck->size)
{
printf("stack is full");
return;
}
stck = malloc(sizeof(stack)); !!!
stck->symbols = (struct table **)malloc(50 * sizeof(struct table*)); !!!
printf("top : %d\n",stck->top);
stck->top = stck->top++;
printf("%d"&stck->top);
stck->symbols[stck->top] = element;
printf("top : %d\n",stck->top);
}
You have to construct your stack before you can push anything onto it. Eg. create function stack_new that will allocate memory for your stack and initialize its members:
stack * stack_new (size_t size)
{
stack * stck = malloc(sizeof(stack));
stck->top = -1;
stck->size = size
stck->symbols = (struct table **)malloc(size * sizeof(struct table*));
return stck;
}
Now, once you properly constructed your stack with above function, you may pass it to push function.
You are passing one stack in a variable called stck, but then allocating a new structure and assigning it to the same pointer. So the stack you pass in is never modified. I don't think you need the first malloc call.
Before you ever call push, you are going to want to malloc space for the stack.
With the !!! lines, you are allocating new memory with each push, which is wrong.
Without the !!! lines, you are never allocating the memory
If you pass a single pointer stack *stck and then malloc inside the function, it will not reflect once you get out the function.
Also, why do you need to allocate memory for table for 50 pointers each time you want to push?
Do it like below:
struct table
{
//members go here
};
typedef struct
{
struct table **symbols;
int top;
int size;
}stack;
struct table *get_elem(void)
{
//logic for getting elements go here
}
void stack_push(stack *stck, struct table *element)
{
if(stck->top==stck->size)
{
printf("Stack Full\n");
return;
}
stck->top++;
stck->symbols[stck->top] = element;
return;
}
void stack_func()
{
struct table *elem = NULL;
stack *stck = (stack *)malloc(sizeof(stack));
if(NULL==stck)
{
return;
}
stck->top = -1;
stck->symbols = (struct table **)malloc(50 * sizeof(struct table *));
if(NULL == stck->symbols)
{
free(stck);
return;
}
stck->size = 49;
elem = get_elem();
//do check here for correctness of elem returned from get_elem
stack_push(stck, elem);
return;
}
Hope this helps! : )