If I want to end the compiling of a void function, do I break or return NULL?
This is a piece of code that returns an error.
void addUser( const char *name ) {
//create Usernode and void *data (user w/ friends)
//check to see if User already exists
if ( findUser(name) != NULL) {
return;
}
//create data for node
User *registeredData = malloc(sizeof(struct User_struct)); //first user Data
registeredData->name = name;
//create a Friends
//put this in file create Friends
Friends initAmigos;
initAmigos = (Friends)malloc(sizeof(struct Friends_struct)); //NOTE: NO POINTERS HERE
//set Friends list to Null
initAmigos->amigos_Queue = que_create( NULL );
registeredData->amigos = initAmigos;
//void que_insert( QueueADT queue, void *data )
que_insert( initAmigo , registeredData);
printf("%s User was inerted \n", name);
}
You can "return;" from a void function, which stops execution execution of the function, and returns to the calling code.
You said "stop compiling", which shows a misunderstand of the difference between execution and compiling. Compiling+linking converts your code (in its entirety) into something that can be executed on a processor. Functions are then "run" on that processor until they complete. A void function can signal that its complete by having a return statement that has no value.
Related
(English is not my first language, so forgive me)
My code is supposed to go over an assembly file, line by line, and when it finds label in the pattern ':', it supposed to add it as the head of a linked list.
When I tried to debug the function I can actually see that it fills the linked list as planned. but right after the last line of the file, it deletes everything and the head of the of list becomes NULL.
When I tried to put a breakpoint after the loop ends, Visual issued a warning 'This breakpoint will not currently be hit. No executable code of the debugger's target code type is associates with this line' .
Here is the code:
//function input: 1. files 2.head of linked list
//function finds label in file and add label to linked list
//function used in the first iteration
void create_labels_list(int argc, char* argv[], label* head)
{
char newline[MAX_LINE];
FILE* assem_file = fopen(argv[1], "r");
int line_count = 1;//we want to know the number of line of the label so we could get to it when needed
if (assem_file == NULL)
{
exit(1);
}
else
{
while (fgets(newline, MAX_LINE + 1, assem_file) != NULL)//go over the assembly file, line by line
{
clean_line(newline, 0); //get rid of all residuals in line
int i = 0;//index of the chars in the line
char labelname[50];
int labelpc = 0;
for (i; newline[i] != '\0'; i++)//go over the line
{
if (newline[i] == ':')//sign that we have a label in the line. if we do, create a new label in the linked list
{
labelpc = line_count;
copy_string(labelname, newline, 0, i - 1);
head = new_label_in_link_lst(head, labelpc, labelname);
}
}
line_count++;
}
}
fclose(assem_file);
}
it worked a few days ago and I don't know what I changed that ruined it.
Thank You!
Most likely your problem is here: void create_labels_list(int argc, char* argv[], label* head). In this code the value of the head pointer only exists inside the function. After exit from the function the old value which you passed to it will be in effect.
In general you have two ways to work around it:
return the value of the pointer from this function, similar to new_label_in_link_lst.
label *create_labels_list(int argc, char* argv[], label* head) {
...
return head;
}
main () {
label *head = NULL;
...
head = create_labels_list(..., head);
...
}
or you can pass an address of your head to the function in arguments and use re-direction to update its value.
void create_labels_list(int argc, char* argv[], label** head) {
...
*head = new_label_in_link_lst(*head, labelpc, labelname)
...
}
main () {
label *head = NULL;
...
create_labels_list(..., &head);
...
}
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(©, &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(©);
o1.id = -1;
free(o1.name);
o1.name = NULL;
object_cpy(©, &o1);
print_object(©);
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(©, &o1);
print_object(©);
print_object(&o1);
object_dtor(&o1);
object_dtor(©);
}
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(©, &test)) {
return (1);
}
Object_Destructor(&test);
Object_Destructor(©);
return (0);
}
First off, I am not a programmer, I do electrical engineering. I have done some programming, but would never say that I am a good programmer. This question will probably be downvoted, but that is ok because I have been trying to do this for two months now.
I no nothing about event.h, but I have an existing code that works and uses this. It goes like this (I changed some things to hide information, but the code works):
struct event_base *base;
struct event *read_event;
struct event *signal_event;
typedef struct sample_ctx {
sens_handle_t *sens_handler;
sens_data_t data;
} sample_ctx_t;
// signal handler to break the event loop
void
signal_handler(evutil_socket_t sock, short event, void *user_data)
{
event_base_loopbreak(base);
}
// receive callback
void
sens_recv_cb(evutil_socket_t sock, short event, void *user_data)
{
static int i = 0;
int timeout = 0;
static struct timeval timestamp;
struct timeval timestamp2;
struct timeval diff;
sens_status_t status;
sample_ctx_t *ctx;
ctx = (sample_ctx_t *)user_data;
if (i == 0) {
gettimeofday(×tamp, NULL);
i = 1;
}
status = sens_read(&ctx->data, ctx->sens_handler);
if ((status == SENS_SUCCESS) &&
!isnan(ctx->data.info1) &&
!isnan(ctx->data.info2) &&
!isnan(ctx->data.info3) &&
!isnan(ctx->data.info4)) {
fprintf(stderr, "%lf %lf %lf %lf\n",
ctx->data.info1,
ctx->data.info2,
ctx->data.info3,
ctx->data.info4);
gettimeofday(×tamp, NULL);
} else {
gettimeofday(×tamp2, NULL);
timersub(×tamp2, ×tamp, &diff);
timeout = diff.tv_sec + (diff.tv_usec / 1000000);
}
}
int main()
{
int fd;
status_t status;
sample_ctx_t ctx;
memset(&ctx, 0, sizeof(ctx));
status = sensor_open(&fd, &ctx.gps_handler);
if (status != V2X_SUCCESS) {
fprintf(stderr, "Open failed ... sensor might not be running\n");
goto deinit_4;
}
base = event_base_new();
if (!base) {
fprintf(stderr, "Failed to create event base\n");
goto deinit_3;
}
// register for the read events
read_event = event_new(base, fd, EV_PERSIST|EV_READ, sens_recv_cb, &ctx);
if (!read_event) {
fprintf(stderr, "Failed to create read event\n");
goto deinit_2;
}
// register for the SIGINT signal on ctrl + c key combo
signal_event = evsignal_new(base, SIGINT, signal_handler, NULL);
if (!signal_event) {
fprintf(stderr, "Failed to create signal event\n");
goto deinit_1;
}
event_add(read_event, NULL);
evsignal_add(signal_event, NULL);
event_base_dispatch(base);
evsignal_del(signal_event);
deinit_1:
event_free(read_event);
deinit_2:
event_base_free(base);
deinit_3:
sensor_close(ctx.sens_handler);
deinit_4:
return 0;
}
This code retrieves data from a sensor and prints it to the screen. It's purpose is pretty simple, but the way it has to be done is what is complicated; for me at least.
Ok, so in the sens_recv_cb function, the ctx->data is printed to the screen, but I need to access that in the main function. The only time this function is called is in the event_new function in main. Is there a way get that data in main? Like lets say I just want to print ctx->data.info1 in main while still printing out everything from before in the sens_recv_cb function.
Is what I want to do possible without changing the entire code?
Because main and sens_recv_cb are asynchronous, you'll need a way to signal between them and a way for the call-back to store the data. You can combine both with a linked list:
struct node {
sample_ctx_t data;
struct node *next;
struct node *previous;
}
struct node *head = NULL;
struct node *tail = NULL;
The event handler adds to the head of the list and the main function removes them from the tail. It's a FIFO. You'll need to use atomic operations when reading/writing data to the list. The links provide what you need to know, and if you search, you'll find lots of example code around here and at other sites. You can probably find an open source, thread-safe linked list implementation on GitHub.
Basically, when the list is empty, there's nothing for main to consume.
mon_param is allocated memory by the main process invoking the thread function.
This function will be invoked by multiple threads.So, can I safely assume that it is thread safe as I am using only the variables on the stack?
struct table* get_row_of_machine(int row_num,struct mon_agent *mon_param)
{
struct table *table_row = mon_param->s_table_rows;
if(row_num < mon_param->total_states)
{
table_row = table_row + row_num;
}
return table_row;
}
//in the main function code goes like this ....
int main()
{
int msg_type,ret;
while(!s_interrupted)
{
inter_thread_pair = zsock_new(ZMQ_PAIR);
if(inter_thread_pair != NULL)
zsock_bind (inter_thread_pair, "inproc://zmq_main_pair");
int ret_val = zmq_poll(&socket_items[0], 1, 0); // Do not POLL indefinitely.
if(socket_items[0].revents & ZMQ_POLLIN)
{
char *msg = zstr_recv (inter_thread_pair); //
if(msg != NULL)
{
struct mon_agent *mon_params;
//This is where mon_params is getting its memory
mon_params = (struct mon_agent*)malloc(sizeof(struct mon_agent));
msg_type = get_msg_type(msg);
if(msg_type == /*will check for some message type here*/)
{
struct thread_sock_params *thd_sock = create_connect_pair_socket(thread_count);
// copy the contents of thread_sock_params and also the mon_params to this struct
struct thread_parameters parameters;
parameters.sock_params = thd_sock;
parameters.params = mon_params; //mon_params getting copid here.
//Every time I receive a particular message, I create a new thread and pass on the parameters.
//So, each thread gets its own mon_params memory allocated.
ret = pthread_create(&thread,NULL,monitoring_thread,(void*)¶meters);
and then it goes on like this.
}
}
}
and the code continues..... there is a breakpoint somewhere down..
}
}
void* mon_thread(void *data)
{
// First time data is sent as a function parameter and later will be received as messages.
struct thread_parameters *th_param = (struct thread_parameters *)data;
struct mon_agent *mon_params = th_param->params;
zsock_t* thread_pair_client = zsock_new(ZMQ_PAIR);
//printf("Value of socket is %s: \n",th_param->socket_ep);
rc = zsock_connect(thread_pair_client,th_param->sock_params->socket_ep);
if(rc == -1)
{
printf("zmq_connect failed in monitoring thread.\n");
}
while(!s_interrupted)
{
int row;
//logic to maintain the curent row.
//also receive other messages from thread_pair_client czmq socket.
run_machine(row,mon_params);
}
}
void run_machine(int row_num, struct mon_agent *mon_params)
{
struct table* table_row = get_row_of_state_machine(row_num,mon_param);
}
In short, no.
The way to make parameters thread safe is by design.
There is no fool proof way to do this or a rule of thumb. If you know your codes design well enough and you know no other thread will access the same struct then it's possibly thread safe.
If you do know some other thread might try to access the struct you can use all sorts of synchronization primitives like mutexes, critical sections, semaphores or more generally locks.
So I've got a weird problem and can't seem to solve it. I have an ADT called TEAM:
typedef struct Team {
char *name;
int points;
int matches_won;
int goal_difference;
int goals_for;
}TEAM;
I created a function to initialize variables of the TEAM* type with a given name:
TEAM *createTEAM (char *name){
int error_code;
if (name != NULL){
if(strcmp(name, "") != 0){
TEAM *new_team = (TEAM*)malloc(sizeof(TEAM));
new_team->name = (char*)malloc(sizeof(char)*strlen(name));
strcpy(new_team->name, name);
new_team->points = 0;
new_team->matches_won = 0;
new_team->goal_difference = 0;
new_team->goals_for = 0;
return new_team;
}else{
error_code = EMPTY_STRING_CODE;
}
} else {
error_code = NULL_STRING_CODE;
}
printf("Erro ao criar time.\n");
printError(error_code);
return NULL;
}
I also created a function to delete one of these TEAM* variables properly:
void deleteTEAM (TEAM *team_to_remove){
free(team_to_remove->name);
team_to_remove->name = NULL;
free(team_to_remove);
team_to_remove = NULL;
}
But when one or multiple test functions that I created (example below) run, the program sometimes crashes, sometimes doesn't. I've noticed that changing the names I use affects whether it crashes or not, even if they don't affect the test results.
int create_team_01(){
int test_result;
TEAM *Teste = createTEAM("Cruzeiro");
if (strcmp(Teste->name, "Cruzeiro") == 0){
test_result = TRUE;
}else test_result = FALSE;
_assert(test_result); //just a macro function that will check the argument and return 1 if it's false
deleteTEAM(Teste);
return 0;
}
I don't see any problems with memory allocation or freeing. Still, the debugger complains a lot about the first free() (can't find bounds) of the deleteTEAM function. Any ideas? Thanks a lot in advance for any help.
P.S.: I've even tried checking the mallocs' results, but it doesn't seem to be the problem either, so I removed it for the sake of simplicity.