I am working on building a threads library and for some reason have run into a simple malloc problem that I can't fix right now. I'm sure it's something simple I'm just missing it.
In my main.c I have the following code:
//declare testSem
tasem_t testSem;
int main(int argc, char **argv){
ta_libinit();
//initialize testSem
ta_sem_init(&testSem, 5);
//wait test
ta_sem_wait(&testSem);
the relevant code in my thread library is as follows:
void ta_sem_init(tasem_t *sema, int value)
{
//malloc the semaphore struct
sema = malloc(sizeof(tasem_t));
//error check
if(sema == NULL)
{
printf("could not malloc semaphore");
exit(0);
}
//initialize with the given value
sema->val = value;
printf("SemaVal = %i\n", sema->val);
}
void ta_sem_wait(tasem_t *sema)
{
printf("SemaVal = %i\n", sema->val);
if(sema->val <= 0)
{
//not done yet
printf("SWAPPING\n");
}
else
{
printf("SemaVal = %i\n", sema->val);
sema->val = sema->val + 1;
}
}
Here is the struct from my header file:
//struct to store each semas info
typedef struct tasem_t_struct
{
//value
int val;
//Q* Queue
//int numThreads
}tasem_t;
The output I get from this is:
SemaVal = 5
SemaVal = 0
SWAPPING
So evidently, I'm not mallocing my struct correctly as the value inside is lost once I go out of scope. I know I must just be forgetting something simple. Any ideas?
You can't seem to decide who's responsible for allocating your tasem_t structure. You have a global variable for it and pass its address to ta_sem_init. But then you have ta_sem_init dynamically allocate a brand new tasem_t structure, saving its address to sema, a local function argument, so that address gets lost when it falls out of scope.
Pick one, either:
Make ta_sem_init initialize an existing tasem_t variable.
Make ta_sem_init allocate and initialize a new tasem_t structure and then return its address (either directly or via a tasem_t** output parameter).
Related
I'm currently working on sorting algo. project. We have a limited amount of operations we can use and we are allowed to only use 2 stacks. One of the operations is called pushA and pushB.
The push operation is supposed to push the top value of one stack to the top of the other stack.
This is my current implementation:
typedef struct stack
{
struct stack *prev;
int data;
int size;
struct stack *next;
} t_list_a, t_list_b;
int main(int argc, char *argv[])
{
t_list_a *tail_a;
if (!(ft_isdigit(argv, argc)) || !(checkDups(argv, argc)))
return (1);
tail_a = createList(tail_a, argv, argc);
}
t_list_a *createList(t_list_a *tail_a, char **argv, int argc)
{
int i;
tail_a = firstNode_A(ft_atoi(argv[argc - 1]));
i = argc - 2;
while (i > 0)
{
tail_a = addEnd_A(tail_a, ft_atoi(argv[i]));
i--;
}
tail_a->size = argc;
return (tail_a);
}
firstNode_A and addEnd just either creates the first node or adds a node to the other
Now to the issue
void pushB(t_list_a *tail_a, t_list_b *tail_b)
{
if (!tail_b)
tail_b = firstNode_B(tail_a->data);
else
tail_b = addEnd_B(tail_b, tail_a->data);
tail_a = delLast_A(tail_a);
}
ISSUE:
If I access tail_b.data it's now accessible and tail_a is updated accordingly. However, If I try to declare a t_list_b *tail_b in my main it's not accessible.
I do understand the issue that the struct ptr to the struct is not accessible outside the local scope. However, I don't know how to remedy it.
I've tried creating a double ptr inside the struct and outside and giving the address of tail_a and tail_b to the ptr.
I was thinking to create an array of structs.
P.S:
I'm a bit lost, also this is my second time asking a question so I expect there are some flaws in "how I ask". I would appreciate it a lot if you could indicate how I could ask my questions better so I can learn. Thank you.
I'm a beginner in C. I currently have a task to create a program having multiple queues. How should i correct this? From my understanding, is supposed to clear all of the queues that where created. As currently i think i have memory leaks.
#include <stdio.h> //printf etc
#include <stdlib.h> //malloc calloc realloc free
#include <stdint.h>
/* number of message queues */
#define MSGQS_LEN 5
/* number of nodes in the message queue */
#define CAPACITY 5
typedef struct _node {
const char* message;
struct _node* next;
} node_t;
typedef struct {
char qName;
node_t *front, *rear;
} msg_queue_t;
typedef struct {
msg_queue_t **queues;
} MsgQs_t;
Your code has several problems.
if(msg_queues < 0)
exit(EXIT_FAILURE);
This test is not correct, msg_queues will be NULL if malloc failed for some reason, the test should read.
if(msg_queues == NULL)
exit(EXIT_FAILURE);
/* Relinquishes all resources currently held by a MsgQs_t.
The pointer to the MsgQs_t in question is set to NULL. */
MsgQs_t* unloadMsgQs(){
MsgQs_t *msg_queues;
msg_queues = NULL;
return(msg_queues);
}
You allocate a variable on the stack, initialize it to NULL and return NULL from this function.
What you actually want to do is pass a MsqQs_t* to unloadMsgQs and use this pointer as an argument to free, something like this
void unloadMsgQs(MsgQs_t *msg_q) {
if(msg_q) {
free(msg_q);
}
}
If you want to set the msg_q pointer to NULL so that it can't be reused anymore, you should probably do something like.
void unloadMsgQs(MsgQs_t **msg_q) {
if(msg_q && *msg_q) {
free(*msg_q);
*msg_q = NULL;
}
}
From what I see, my advice would be to read some more books / tutorials on programming with C and pointers in general, because it seems you don't quite grasp the basics yet (which is nothing to be ashamed of of course!)
You have to call free with the pointer value returned from malloc. For this you have to pass the pointer to unloadMsgQs as an argument.
If this function is supposed to set the pointer to NULL in the caller, you have to pass the address of the pointer.
Note that malloc's return value to indicate an error is NULL not a value < 0.
/* Returns a pointer to MsgQs_t structure and through which multiple message queues can be subsequently created.
Each individual message queue is to be identified by a unique identifier. */
MsgQs_t* initializeMsgQs(){
MsgQs_t* msg_queues;
msg_queues = malloc(sizeof(MsgQs_t));
if(msg_queues == NULL)
exit(EXIT_FAILURE);
return(msg_queues);
}
/* Relinquishes all resources currently held by a MsgQs_t.
The pointer to the MsgQs_t in question is set to NULL. */
void unloadMsgQs(MsgQs_t **msg_queues){
if(msg_queues != NULL)
{
free(*msg_queues);
*msg_queues = NULL;
}
}
/* sample use in main() */
int main(int argc, char **argv)
{
MsgQs_t* msg_queues;
msg_queues = initializeMsgQs();
/* ... */
unloadMsgQs(&msg_queues);
return 0;
}
I'm working on INI-style configuration parser for some project, and I gets next trouble.
I have 3 structures:
typedef struct {
const char* name;
unsigned tract;
int channel;
const char* imitation_type;
} module_config;
typedef struct {
int channel_number;
int isWorking;
int frequency;
int moduleCount;
} channel_config;
typedef struct {
int mode;
module_config* module;
channel_config* channel;
} settings;
And I have function for handling data in my INI-file (I working under inih parser): [pasted to pastebin cause too long]. Finally, in main(), I did the next:
settings* main_settings;
main_settings = (settings*)malloc(sizeof(settings));
main_settings->module = (module_config*)malloc(sizeof(module_config));
main_settings->channel = (channel_config*)malloc(sizeof(channel_config));
if (ini_parse("test.ini", handler, &main_settings) < 0) {
printf("Can't load 'test.ini'\n");
return 1;
}
In result, binary crashes with memory fault. I think (no, I KNOW), what I'm incorrectly allocating the memory in handler(), but I does not understand, where I do it wrong. I spent all night long trying to understand memory allocating, and I'm very tired, but now me simply interestingly, what I'm doing wrong, and HOW to force this working fine.
P.S. Sorry for ugly english
The problem seems to be related to the reallocation of your structs:
pconfig = (settings *) realloc(pconfig, (module_count + channel_count) * sizeof(channel_config));
pconfig->module = (module_config *) realloc(pconfig->module, module_count * sizeof(module_config));
pconfig->channel = (channel_config *) realloc(pconfig->channel, channel_count * sizeof(channel_config));
First of all, you must not reallocate the main settings struct. Since your handler will always be called with the original pconfig value, the reallocation of the module and channel arrays has no effect, and you'll access freed memory.
Also when reallocating the module and channel arrays you should allocate count + 1 elements, since the next invocation of handler might assign to the [count] slot.
So try to replace the three lines above with:
pconfig->module = (module_config *) realloc(pconfig->module, (module_count + 1) * sizeof(module_config));
pconfig->channel = (channel_config *) realloc(pconfig->channel, (channel_count + 1) * sizeof(channel_config));
So here is my issue, I have been trying to figure this out for the last 5 hours, I have a header file, a tester file, and a c source file. I would really like to understand what is happening and why so I can avoid the issue in the future. The header file declares the struct but does not define it:
typedef struct Stack *StackP;
and in my source file, Stack.c I have defined the stack:
struct Stack
{
int top;
int capacity;
int count;
ItemT items;
};
where ItemT is defined as char *
in the tester file, the call goes:
StackP stackPtr = newStack();
and what I have for my newStack function located in the c source file is:
StackP newStack(void) {
struct Stack stack1;
StackP stackPtr = &stack1;
(stackPtr->items) = (ItemT)malloc(DEFAULT_CAPACITY*sizeof(ItemT));
(stackPtr->top) = -1;
(stackPtr->capacity) = DEFAULT_CAPACITY;
(stackPtr->count) = 0;
fprintf(stderr, "\nSuccesfully allocated memory to items...\n");
return stackPtr;
}
now, my push function is:
void pushStack(StackP stackPtr, ItemT item) {
if ((stackPtr->count) == (stackPtr->capacity)) {
fprintf(stderr, "\nERROR: Full stack.\n");
}
else {
stackPtr->items = item;
fprintf(stderr, "\nSuccessfully pushed %s on to the stack...\n", stackPtr->items);
(stackPtr->items)++;
(stackPtr->top)++;
(stackPtr->count)++;
}
}
My question is this: Have I don't something wrong in any of these blocks of code.
If I call a function that says:
return (stackPtr->count);
it will return a random set of numbers instead of 0, or 1. For instance, if I push 2 strings to the stack, instead of count being 2, count is 479622 or some other random long number. Why is this happening?
Again, I would like to know what I'm doing wrong and not just correct syntax because I really HAVE to understand this.
The program has undefined behaviour as it is returning the address of a local variable from a function:
StackP newStack(void) {
struct Stack stack1;
StackP stackPtr = &stack1;
return stackPtr;
}
stack1 no longer exists when newStack exits. stackPtr must point to dynamically allocated memory if it is to exist beyond the scope of the function:
StackP newStack(void) {
struct Stack stack1;
StackP stackPtr = malloc(sizeof(*stackPtr));
if (stackPtr)
{
}
return stackPtr;
}
See Do I cast the result of malloc?
I am very much stuck in the following issue. Any help is very much appreciated!
Basically I have a program wich contains an array of structs and I am getting a segmentation error when I call an external function. The error only happens when I have more than 170 items on the array being passed.
Nothing on the function is processed. The program stops exactly when accessing the function.
Is there a limit for the size of the parameters that are passed to external functions?
Main.c
struct ratingObj {
int uid;
int mid;
double rating;
};
void *FunctionLib; /* Handle to shared lib file */
void (*Function)(); /* Pointer to loaded routine */
const char *dlError; /* Pointer to error string */
int main( int argc, char * argv[]){
// ... some code ...
asprintf(&query, "select mid, rating "
"from %s "
"where uid=%d "
"order by rand()", itable, uid);
if (mysql_query(conn2, query)) {
fprintf(stderr, "%s\n", mysql_error(conn2));
exit(1);
}
res2 = mysql_store_result(conn2);
int movieCount = mysql_num_rows(res2);
// withhold is a variable that defines a percentage of the entries
// to be used for calculations (generally 20%)
int listSize = round((movieCount * ((double)withhold/100)));
struct ratingObj moviesToRate[listSize];
int mvCount = 0;
int count =0;
while ((row2 = mysql_fetch_row(res2)) != NULL){
if(count<(movieCount-listSize)){
// adds to another table
}else{
moviesToRate[mvCount].uid = uid;
moviesToRate[mvCount].mid = atoi(row2[0]);
moviesToRate[mvCount].rating = 0.0;
mvCount++;
}
count++;
}
// ... more code ...
FunctionLib = dlopen("library.so", RTLD_LAZY);
dlError = dlerror();
if( dlError ) exit(1);
Function = dlsym( FunctionLib, "getResults");
dlError = dlerror();
(*Function)( moviesToRate, listSize );
// .. more code
}
library.c
struct ratingObj {
int uid;
int mid;
double rating;
};
typedef struct ratingObj ratingObj;
void getResults(struct ratingObj *moviesToRate, int listSize);
void getResults(struct ratingObj *moviesToRate, int listSize){
// ... more code
}
You are likely blowing up the stack. Move the array to outside of the function, i.e. from auto to static land.
Another option is that the // ... more code - array gets populated... part is corrupting the stack.
Edit 0:
After you posted more code - you are using C99 variable sized array on the stack - Bad IdeaTM. Think what happens when your data set grows to thousands, or millions, of records. Switch to dynamic memory allocation, see malloc(3).
You don't show us what listsize is, but I suppose it is a variable and not a constant.
What you are using are variable length arrays, VLA. These are a bit dangerous if they are too large since they usually allocated on the stack.
To work around that you can allocate such a beast dynamically
struct ratingObj (*movies)[listSize] = malloc(sizeof(*movies));
// ...
free(movies);
You'd then have in mind though that movies then is a pointer to array, so you have to reference with one * more than before.
Another, more classical C version would be
struct ratingObj * movies = malloc(sizeof(*movies)*listsize);
// ...
free(movies);