I'm trying to implement generic stack in C, but I can't print value that I pushed. Here is the code
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <memory.h>
typedef struct{
void *elems;
int sizeOfElems;
int allocated;
int lenght;
}stack;
void allocate_stack(stack *s, int sizeOfElements){
assert(sizeOfElements > 0);
s->sizeOfElems = sizeOfElements;
s->allocated = 2;
s->lenght = 2;
s->elems = malloc(sizeOfElements * s->allocated);
}
void deallocate_stack(stack *s){
free(s->elems);
}
void push_elem(stack *s, void *elem){
s->lenght += 1;
if(s->allocated == s->lenght){
realloc(s, s->lenght * s->sizeOfElems);
s->lenght *= 2;
}
void *target = (char *)s->elems + s->lenght * s->sizeOfElems;
memcpy(target, elem, s->sizeOfElems);
}
void pop_elem(stack *s, void *elemAddr){
void *source = (char *)s->elems + (s->lenght-1) * s->sizeOfElems;
memcpy(elemAddr, source, s->sizeOfElems);
s->lenght -=1;
}
int main(){
stack s;
allocate_stack(&s, 1);
char a = 'a';
push_elem(&s, &a);
char *elem = NULL;
pop_elem(&s, elem);
printf("%s", elem);
deallocate_stack(&s);
return 0;
}
The problem is that I don't get anything when I run the program, just press return to close the window. I'm programming on Linux using GCC toolkit.
In your push_elem:
s->lenght += 1;
if(s->allocated == s->lenght){
realloc(s, s->lenght * s->sizeOfElems);
s->lenght *= 2;
}
It seems like you are trying to re-allocate space if you run out, but your default value of 2 for allocated is going to stay as it is, you should probably do something like:
if (s->allocated < s->lenght) {
realloc(s->elems, ....)
//Increase both allocated and length to represent the current state of the stack
}
Notice that in the realloc() call you are passing s, which is in the stack, this won't do what you want: http://pubs.opengroup.org/onlinepubs/7908799/xsh/realloc.html As per your structure you should be passing s->elems
Also, before calling pop_elem, you are assigning NULL to elem. Inside your pop_elem, this is where you are trying to do a memcpy() to. To do this you will have to allocate memory:http://pubs.opengroup.org/onlinepubs/009695399/functions/memcpy.html
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments