stack of coins, push function (C) - c

I got a stack of coins, which are made this way:
#define MAX_PAIS 20
typedef int VALUE;
typedef struct {
VALUE value;
char country [MAX_PAIS];
} COIN;
and
#define MAXSTACK 100
typedef struct {
int top;
ELESTACK item [MAXSTACK];
} STACK;
to push a coin into the stack, I do:
STATUS push(STACK *stc, const ELESTACK *ele) {
//stuff
stc->top++;
retorno = copyEleStack(stc->item[stc->top], ele);
//stuff
}
the important thing is the copyElestack thing, my ide gives me an error, it says this function needs the first argument to be struct elestack * but is elestack... the mentioned function do that:
ELESTACK *copyEleStack(ELESTACK *dst, const ELESTACK *src) {
int retorno;
retorno = copyCoin(dst, src);
if (retorno == ERROR) {
return NULL;
}
}
and copycoin:
STATUS copyCoin(COIN * pDest, const COIN * pOrigin) {
pDest->value = pOrigin->value;
strcpy(pDest->country, pOrigin->country);
if (pDest->value != 0 && pDest->country != NULL) {
return OK;
}
return ERROR;
I think this might be something related to the pointers, but I'm not seeing it right now, any help would be nice

Your compiler is telling you the right thing. copyEleStack takes an ELESTACK*, but you are passing it an ELESTACK value. Try &stc->item[stc->top] or alternately (stc->item+stc->top)

Related

Freeing memory gives segmentation fault [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I've been trying to work with structures, pointers and memory in C.
I have created this structure
typedef struct {
int id;
char *name;
} Object;
here is constructor
void object_ctor(Object *o, int id, char *name)
{
o->id = id;
o->name = malloc(sizeof(name));
if(sizeof(o->name)!=sizeof(name))
{
o->name=NULL;
}
else
{
strcpy(o->name, name);
}
}
here is decleration of o1
char tmp_name[] = "Hello 1";
Object o1;
object_ctor(&o1, 1, tmp_name);
here is destructor
void object_dtor(Object *o)
{
if(o->name != NULL)
{
free(o->name);
o->name = NULL;
}
}
printing object
void print_object(Object *o)
{
printf("ID: %d, NAME: %s\n", o->id, o->name);
}
calling copy
Object copy;
print_object(object_cpy(&copy, &o1));
and I´m trying create a copy of one structure to another (I have already constructed them).
Object *object_cpy(Object *dst, Object *src)
{
if(src!=NULL)
{
const size_t len_str=strlen(src->name)+1;
dst->name = malloc(10000000);
dst->id = src->id;
strncpy (dst->name, src->name,len_str);
}
if (strcmp(dst->name,src->name)!=0)
{
dst->name = NULL;
}
return dst;
}
But then when I'm trying to free both copy and original src I get a segmentation fault. I've been trying to run it through gdb and it said that I'm freeing same memory twice so I assume that the code for copying is wrong, but I don't know where.
And here is code that gives me segmentation fault
printf("\nCOPY EMPTY\n");
object_dtor(&copy);
o1.id = -1;
free(o1.name);
o1.name = NULL;
object_cpy(&copy, &o1);
print_object(&copy);
print_object(&o1);
I´m including these libraries
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
I'm using the std=c99 flag for to compile.
There is at least a problem here:
void object_ctor(Object *o, int id, char *name)
{
o->id = id;
o->name = malloc(sizeof(name));
if (sizeof(o->name) != sizeof(name))
{
o->name = NULL;
}
else
{
strcpy(o->name, name);
}
}
sizeof(name) is not the length of the string pointed by name. You need strlen(name) + 1 (+1 for the NUL terminator).
And your test if (sizeof(o->name) != sizeof(name)) is pointless, and I'm not sure what you're trying to achieve here.
You probably want this:
void object_ctor(Object *o, int id, char *name)
{
o->id = id;
o->name = malloc(strlen(name) + 1);
if (o->name != NULL)
strcpy(o->name, name);
}
There are similar problems in object_cpy:
pointless use of strncpy
pointless allocation of a 10Mb buffer
pointless test strcmp(dst->name, src->name)
You probably want this:
Object *object_cpy(Object *dst, Object *src)
{
if (src != NULL)
{
const size_t len_str = strlen(src->name) + 1;
dst->name = malloc(len_str);
if (dst->name != NULL)
{
dst->id = src->id;
strcpy(dst->name, src->name);
}
}
return dst;
}
With these corrections following code works fine:
int main()
{
char tmp_name[] = "Hello 1";
Object o1, copy;
object_ctor(&o1, 1, tmp_name);
object_cpy(&copy, &o1);
print_object(&copy);
print_object(&o1);
object_dtor(&o1);
object_dtor(&copy);
}
Event if this is not directly an answer to your problem, I'll give you how I organize my code in order to avoid memory problem like yours.
First, it all resolve around a structure.
To each structure, if needed, I do a "Constructor" and a "Destructor".
The purpose of the constructor is simply to set the structure in a coherent state. It can't never fail (implying that any code that could fail, like malloc, should not be in the constructor).
The purpose of the destructor is to clean the structure.
One little trick that I like to use is to put the constructor in a macro, allowing me to do something like 'Object var = OBJET_CONSTRUCTOR'.
Of course, it's not alway possible, it's up to you to be carreful.
For your code, it could be :
typedef struct {
int id;
char *name;
} Object;
#define OBJECT_CONSTRUCTOR {.id = -1,\ \\ Assuming -1 is relevant in your case, like an error code or a bad id value. Otherwise, it's useless.
.name = NULL}
void Object_Constructor(Object *self)
{
Object clean = OBJECT_CONSTRUCTOR;
*self = clean;
}
void Object_Destructor(Object *self)
{
free(self->name);
}
Here we go.
How to use it is simple : You always begin by the constructor, and you alway end by the destructor. That's why it's useless to set the char pointer "name" to NULL in the destructor, because it should not be used after by any other function that the constructor.
Now, you can have "initialisation" function. You can do a plain initialisation (it is your constructor function), or a copy initialisation, etc etc
Just keep in mind that the structure have been called into the constructor. If not, it's the developer fault and you do not have to take that in count.
A behavior that can be nice is, in case of error, to not modify the structure.
Either the structure is entierly modified in succes, or not at all.
For complex structure that can fail at many point, you can do that by "swapping" the result at the end.
void Object_Swap(Object *first, Object *second)
{
Object tmp = OBJECT_CONSTRUCTOR;
tmp = *fisrt;
*first = *second;
*second = tmp;
}
bool Object_InitByPlainList(Object *self, int id, consr char *name)
{
Object newly = OBJECT_CONSTRUCTOR;
bool returnFunction = false;
newly.id = id;
if (!(newly.name = strdup(name))) {
printf("error : %s : strdup(name) : name='%s', errno='%s'.\n", __func__, name, strerror(errno));
goto END_FUNCTION;
}
// Success !
Object_Swap(self, &newly);
returnFunction = true;
/* GOTO */END_FUNCTION:
Object_Destructor(&newly);
return (returnFunction);
}
It may be seem overcomplicated at the first glance, but that organization allow you to add more futur step "that can fail" cleanly.
Now, you can even do something this simply :
bool Object_InitByCopy(Object *dst, Object *src)
{
return (Object_InitByPlainList(dst, src->id, src->name));
}
All you have to do is to say in the documentation :
The first function to be called have to be "Object_Constructor"
After the "Object_Constructor", only the "Object_Init*" function can be called.
The last function to be call have to be "Object_Destructor"
That's all. You can add any "Object_*" function that you whant, like :
void Object_Print(const Object *self)
{
printf("ID: %d, NAME: %s\n", self->id, self->name);
}
Hope this organization will solve your memory problem.
An example :
int main(void)
{
Object test = OBJECT_CONSTRUCTOR;
Object copy = OBJECT_CONSTRUCTOR;
if (!Object_InitByPlainList(&test, 1, "Hello World !")) {
// The function itself has logged why it has fail, so no need to add error printf here
return (1);
}
Object_Print(&test);
if (!Object_Copy(&copy, &test)) {
return (1);
}
Object_Destructor(&test);
Object_Destructor(&copy);
return (0);
}

Initializing a struct in C

Im having trouble initialising structures (well doing everything actually, but structures first). The struct is first made in a header as follows
typedef enum cell
{
BLANK, RED, CYAN
} Cell;
#define NAMELEN 20
typedef struct player
{
char name[NAMELEN + NULL_SPACE];
Cell token;
unsigned score;
} Player;
void initFirstPlayer(Player * player);
void initSecondPlayer(Player * player, Cell token);
#endif
=======================================================================
and I tried to initialise it here
void initFirstPlayer(Player * player)
{
int randNo = rand() % 2;
if (randNo == 0) {
token = RED;
}
else() {
token = CYAN;
}
player ; p1 = {
"placeholder",
token,
0,
}
}
void initSecondPlayer(Player * player, Cell token)
{ }
What is the correct way to initialise this player struct?
I suspect this should work for you. Use a generic initPlayer function. Use that to allocate memory for the player and set the initial values. Be sure to also include a freePlayer function where you free() the player when you're done.
#include <stdlib.h>
#include <string.h>
Player* initPlayer()
{
Player* player = malloc(sizeof(Player));
int randNo = rand() % 2;
if (randNo == 0) {
player->token = RED;
}
else {
player->token = CYAN;
}
const char* initName = "placeholder";
strcpy(player->name, initName);
player->score = 0;
return player;
}
void freePlayer(Player* p)
{
free(p);
}
The way you'd use this would be like so:
int main()
{
Player* p1 = initPlayer();
Player* p2 = initPlayer();
play(p1, p2);
freePlayer(p1);
freePlayer(p2);
}
Assuming you have at least C99 support, so that compound literals and designated initializers are available to you, then you can use:
void initFirstPlayer(Player *player)
{
*player = (Player){ .token = rand() % 2 ? CYAN : RED,
.score = 0,
.name = "placeholder"
};
}
This does a structure assignment to the variable whose address is passed to the function. It compresses it all into one statement; you can split it out into several if you wish. This is an occasion where the ternary ? : operator is useful. You might prefer (rand() % 2) with the extra parentheses; I'd probably add them as often as I'd omit them.
The compound literal comes from (typename){ ...initializer for typename... }.
The designated initializers are the .member = value notations.
If you're stuck with C90 support, you have to work harder, perhaps creating a local variable with the correct information and then doing the structure assignment.
void initFirstPlayer(Player *player)
{
Player p1 = { "placeholder", rand() % 2 ? CYAN : RED, 0 };
*player = p1;
}
Now the onus is on you to list the initializers in the correct sequence.
Another way is to receive the player you want to inicialize as parameter:
void initPlayer(Player* player)
{
int randNo = rand() % 2;
if (randNo == 0) {
player->token = RED;
}
else {
player->token = CYAN;
}
const char* initName = "placeholder";
strcpy(player->name, initName);
player->score = 0;
}
int main() {
Player p1;
initPlayer(&p1);
}
You can have an array of players or allocate dinamically with malloc.

How do you use a typedef struct for a FIFO?

I just started programming in C for school. I am being asked to do a program that uses a FIFO struct to resolve math problems. I got the folowing code on the internet for a FIFO, I just don't know how to use it. I tried a lot of things and I can't find anything useful on the internet or maybe that I just don't know the right thing to research but could you please help me? Thanks!
#include <stdio.h>
#include <stdlib.h>
typedef struct pile
{
int donnee;
struct pile *precedent;
} Pile;
void pile_push(Pile **p_pile, int donnee)
{
Pile *p_nouveau = malloc(sizeof *p_nouveau);
if (p_nouveau != NULL)
{
p_nouveau->donnee = donnee;
p_nouveau->precedent = *p_pile;
*p_pile = p_nouveau;
}
}
int pile_pop(Pile **p_pile)
{
int ret = -1;
if (p_pile != NULL)
{
Pile *temporaire = (*p_pile)->precedent;
ret = (*p_pile)->donnee;
free(*p_pile), *p_pile = NULL;
*p_pile = temporaire;
}
return ret;
}
void pile_clear(Pile **p_pile)
{
while (*p_pile != NULL)
{
pile_pop(p_pile);
}
}
I tried doing this:
int main()
{
int return_val;
Pile pile;
pile_push(Pile, 5);
return_val = pile_pop(Pile);
printf(return_val);
}
and got this error:
expected expression before 'Pile'
too few arguments to function 'pile_push'
You have mixed up Pile and pile which is the issue with the first warning. The functions expect a pointer to a pointer to a Pile. That is: They update the value of a pointer, so they need to be passed a reference to a pointer. Your use of printf is also wrong.
int main()
{
int return_val;
Pile *pile = NULL;
pile_push(&pile,5);
return_val = pile_pop(&pile);
printf("return_val is: %d\n",return_val);
}

Pushing C pointer to stack, getting table

I have two functions defined in C code:
static int luaMp4_load(lua_State *L){
LPP_Mp4 *ret = LPP_Mp4Load(luaL_checkstring(L, 1));
*pushMp4(L) = ret;
return(1);
}
static int luaMp4_play(lua_State *L){
LPP_Mp4Play(*toMp4(L, 1), luaL_checknumber(L, 2));
return 0;
}
which are called one by one in Lua:
Mp4.load(movie)
Mp4:play(60)
Functions pushMp4 and toMp4 are
LPP_Mp4** toMp4 (lua_State *L, int index){
LPP_Mp4** handle = (LPP_Mp4**)lua_touserdata(L, index);
if (handle == NULL) luaL_typerror(L, index, "Mp4");
return handle;
}
LPP_Mp4** pushMp4(lua_State *L) {
LPP_Mp4** newvalue = (LPP_Mp4**)lua_newuserdata(L, sizeof(LPP_Mp4*));
lua_getfield(L, LUA_REGISTRYINDEX, "Mp4");
lua_setmetatable(L, -2);
return newvalue;
}
The problem is, I'm getting a NULL handle in luaMp4_play, and it says that object in the first index of stack is table (while Mp4 expected) - inside of luaL_typerror(lua_State *L, int narg, const char *tname):
const char *msg = lua_pushfstring(L, "%s expected, got %s",
tname, lua_typename(L, lua_type(L,(narg))));
How can I get rid of it?
Edit:
LPP_Mp4 struct:
typedef struct {
struct mp4_read_struct reader;
Mp4AvcNalStruct nal;
struct mp4_video_read_output_struct v_packet;
Mp4AvcDecoderStruct *avc;
Mp4AvcCscStruct *csc;
} LPP_Mp4;
lua_touserdata is a Lua API library function:
LUA_API void *lua_touserdata (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
switch (ttype(o)) {
case LUA_TUSERDATA: return (rawuvalue(o) + 1);
case LUA_TLIGHTUSERDATA: return pvalue(o);
default: return NULL;
}
}
https://github.com/lua/lua/blob/master/src/lapi.c - line 413
I was confused with return(1); in C code and had no doubt that Mp4:load() returns any value
Thanks to Etan Reisner for pointing to it, worked with:
mv = Mp4.load(movie)
mv:play(60)

Memory allocation error for structs with members that are function pointers and void pointers

I have written a straightforward C code that uses an engine to run two different algorithms depending on user input. It uses function pointers to the algorithm methods and objects. There is a nasty memory bug somewhere that I can not track down, so maybe I am allocating memory in the wrong way. What is going wrong?
Below is (the relevant parts of) a minimal working example of the code.
main.c
#include "engine.h"
int main()
{
char *id = "one";
Engine_t eng;
Engine_init(&eng);
Engine_select_algorithm(eng, id);
Engine_run(eng);
}
engine.h
typedef struct _Engine *Engine_t;
engine.c
#include "engine.h"
#include "algorithm_one.h"
#include "algorithm_two.h"
typedef struct _Engine
{
void *p_algorithm;
void (*init)(Engine_t);
void (*run)(Engine_t);
} Engine;
void Engine_init(Engine_t *eng)
{
*eng = malloc(sizeof(Engine));
(*eng)->p_algorithm = NULL;
}
void Engine_select_algorithm(Engine_t eng, char *id)
{
if ( strcmp(id, "one") == 0 )
{
eng->init = Algorithm_one_init;
eng->run = Algorithm_one_run;
}
else if ( strcmp(id, "two") == 0 )
{
eng->init = Algorithm_two_init;
eng->run = Algorithm_two_run;
}
else
{
printf("Unknown engine %s.\n", id); exit(0);
}
eng->init(eng);
}
void Engine_run(Engine_t eng)
{
eng->run(eng);
}
void Engine_set_algorithm(Engine_t eng, void *p)
{
eng->p_algorithm = p;
}
void Engine_get_algorithm(Engine_t eng, void *p)
{
p = eng->p_algorithm;
}
algorithm_one.h
typedef struct _A_one *A_one_t;
algorithm_one.c
#include "engine.h"
#include "algorithm_one.h"
typedef struct _A_one
{
float value;
} A_one;
void Algorithm_one_init(Engine_t eng)
{
A_one_t aone;
aone = malloc(sizeof(A_one));
aone->value = 13.0;
//int var = 10;
Engine_set_algorithm(eng, &aone);
}
void Algorithm_one_run(Engine_t eng)
{
A_one_t aone;
Engine_get_algorithm(eng, &aone);
printf("I am running algorithm one with value %f.\n", aone->value);
// The code for algorithm one goes here.
}
The code for algorithm_two.h and algorithm_two.c are identical to the algorithm one files.
There must be a memory bug involved, because the code runs as given, but if I uncomment the
//int var = 10;
line in algoritm_one.c the code crashes with a segmentation fault.
You pass the wrong thing to Engine_set_algorithm. You are passing the address of a local variable rather than the address of the algorithm. You need to write:
Engine_set_algorithm(eng, aone);
And also Engine_get_algorithm is wrong. You are passed a pointer by value and modify that pointer. So the caller cannot see that modification. You need it to be:
void Engine_get_algorithm(Engine_t eng, void **p)
{
*p = eng->p_algorithm;
}
I think your code would be easier if you defined a type to represent an algorithm. That type would be just a void*, but it would make the code much easier to read. What's more, I would make Engine_get_algorithm return the algorithm.
algorithm Engine_get_algorithm(Engine_t eng)
{
return eng->p_algorithm;
}
void Engine_set_algorithm(Engine_t eng, algorithm alg)
{
eng->p_algorithm = alg;
}

Resources