Pass local variable of a function back to it's parameter - c

I'm wanting to pass a local variable within a function, back through it's pointer parameter (not returned).
My assignment uses a stack data structure, and one criteria that must be used is the Pop() function must have a pointer parameter that is used to return the top-most item on the stack. I have used this before. My program became more complex with a data struct, I started getting either segmentation faults, or the data not being saved after the function's frame popped.
// Definitions
typedef char * string;
typedef enum { SUCCESS, FAIL } result;
typedef enum { INTEGER, DOUBLE, STRING } item_tag;
// Result Check
static result RESULT;
// Item_Tag
typedef struct {
item_tag tag;
union {
int i;
double d;
string s;
} value;
} item;
// Declarations
int STACK_SIZE = 0;
const int MAX_STACK_SIZE = 1024; // Maximum stack size
item stack[1024];
// Pop
result Pop(item *ip){
item poppedItem;
item * pointerReturn = malloc(sizeof(item));
// Check stack size is not 0
if(STACK_SIZE == 0){
return FAIL;
}
// If stack size is only 1, creates a blank stack
else if(STACK_SIZE == 1){
item emptyItem;
// Initialize
emptyItem.tag = INTEGER;
emptyItem.value.i = 0;
// Check top item's tag
poppedItem = stack[0];
// Store top item data based on tag
switch(stack[0].tag){
case STRING:
poppedItem.value.s = stack[0].value.s;
case DOUBLE:
poppedItem.value.d = stack[0].value.d;
default:
poppedItem.value.i = stack[0].value.i;
}
poppedItem.tag = stack[0].tag;
// Allocate memory for parameter, and have it point to poppedItem
ip = malloc(sizeof(poppedItem));
*ip = poppedItem;
// Store empty stack to top of stack
stack[0] = emptyItem;
// Decrease stack size
STACK_SIZE--;
}
// Grab top Item from stack
else{
// Check top item's tag
poppedItem = stack[0];
// Store top item data based on tag
switch(stack[0].tag){
case STRING:
poppedItem.value.s = stack[0].value.s;
case DOUBLE:
poppedItem.value.d = stack[0].value.d;
default:
poppedItem.value.i = stack[0].value.i;
}
poppedItem.tag = stack[0].tag;
// Allocate memory for parameter, and have it point to poppedItem
ip = malloc(sizeof(poppedItem));
*ip = poppedItem;
// Reshuffle Items in Stack
for(int idx = 0; idx < STACK_SIZE; idx++){
stack[idx] = stack[idx + 1];
}
STACK_SIZE--;
}
return SUCCESS;
}
My knowledge with pointers is alright, and memory location/management. But I can't claim to be an expert by any means. I don't exactly know what happens in the background when you're using the function's own pointer parameter as a means of passing data back.
What is the correct syntax to solve this problem?
How can a parameter pass something back?
Thanks in advance!
EDIT*
Since many people are confused. I'll post some snippets. This is an assignment, so I cannot simply post all of it online as that'd be inappropriate. But I think it's okay to post the function itself and have people analyze it. I'm aware it's a bit messy atm since I've edited it several dozen times to try and figure out the solution. Sorry for the confusion. Keep in mind that not all the code is there. just the function in question, and some of the structure.

The function should receive a pointer to a valid object:
item catcher;
myFunc(&catcher); // Pass a pointer to catcher
and the function should modify the object it received a pointer to:
void myFunc(item *itemPointer)
{
itemPointer->variable = stuff;
// or
*itemPointer = someItem;
}
Update:
You're overcomplicating things immensely – there should be no mallocs when popping, and you're leaking memory all over the place.
(Your knowledge of pointers and memory management is far from "alright". It looks more like a novice's guesswork than knowledge.)
It should be something more like this:
result Pop(item *ip){
if (STACK_SIZE == 0){
return FAIL;
}
else {
*ip = stack[0];
for(int idx = 0; idx < STACK_SIZE; idx++){
stack[idx] = stack[idx + 1];
}
STACK_SIZE--;
}
return SUCCESS;
}
but it's better to push/pop at the far end of the array:
result Pop(item *ip){
if (STACK_SIZE == 0){
return FAIL;
}
else {
*ip = stack[STACK_SIZE-1];
STACK_SIZE--;
}
return SUCCESS;
}

Response to the originally posted code:
typedef struct{
variables
}item;
void myFunc(item *itemPointer){
item newItem;
newItem.variable = stuff;
}
int main(){
item * catcher;
myFunc(catcher);
printf("%s\n", catcher.variable);
}
A few issues.
Your program will not compile. variable has to have a type.
void myFunc(item *itemPointer){
item newItem;
newItem.variable = stuff;
}
stuff is not defined; item *itemPointer is not used.
item * catcher pointer has to point to allocated memory. It is not initialized.
Pass arguments via pointers and modify member of the structure like this:
void myFunc(item *itemPointer, const char *string){
itemPointer->variable = string ;
}
Solution like:
void myFunc(item *itemPointer)
{
itemPointer->variable = stuff;
// or
*itemPointer = someItem;
}
is possible, but it assumes that stuff or someItem is a global variable which is not the best programming practice IMO.
Retrieve value from pointer via -> not . operator.
#include <stdio.h>
#include <stdlib.h>
typedef struct{
char * variable;
}item;
void myFunc(item *itemPointer, const char *string){
itemPointer->variable = string ;
}
int main(){
item * catcher;
char *new_string = "new string";
catcher = malloc(sizeof(item));
myFunc(catcher, new_string);
printf("%s\n", catcher->variable);
free(catcher);
return 0;
}
OUTPUT:
new string

Related

How to generically assign a pointer passed into a function in C

I am new to C and wondering how to do some pointer stuff. Specifically here I am wondering how you can pass a pointer into a function and "get a value out of the function". Sort of like this (semi-pseudocode):
assign_value_to_pointer(void* pointer) {
if (cond1) {
pointer = 10;
} else if (cond2) {
pointer = "foo";
} else if (cond3) {
pointer = true;
} else if (cond4) {
pointer = somestruct;
} else if (cond5) {
pointer = NULL;
} else if (cond6) {
// unknown type!
pointer = flexiblearraymember.items[index];
}
}
main() {
void* pointer = NULL;
assign_value_to_pointer(&pointer);
if (cond1) {
assert(pointer == 10);
} else if (cond2) {
assert(pointer == "foo");
} else if (cond3) {
assert(pointer == true);
} else if (cond4) {
assert(pointer == somestruct);
} else if (cond5) {
assert(pointer == NULL);
}
}
Put another way:
p = new Pointer()
assign_a_value(p)
assert(p.value == 10) // or whatever
Basically it is passing the pointer into the function, the function is assigning a value to the pointer, and then you can use that value outside of the function when it returns. You may not know what kind of value you are getting from the function (but that can be handled by extending this to use structs and such), hence the void pointer. The main goal though is just passing a pointer into some function and having it absorb some value.
Wondering how to do this properly in C with a quick example implementation. Doesn't have to cover every case just enough to get started.
I would like to use this to implement stuff like passing in a NULL error object to a function, and if there is an error, it sets the pointer of the error to some error code, etc.
I don't think this should be a broad question, but if it is, it would be helpful to know where to look for a more thorough explanation or examples in source code.
First, I'll answer your question directly, hopefully you understand why you need to be reaaally careful. This can be a useful technique for implementing queues, or communication stacks - but you need to be CERTAIN that you can regain track of what types are being stored or your program logic will totally break. I'll then try to briefly cover some of the use cases and some methods of making it safe(r).
Simple example doing exactly what you said
#include <stdio.h>
#include <stdlib.h>
//Some basic error type for reporting failures
typedef enum my_error
{
ERROR_NONE = 0,
ERROR_FAIL = 1,
} my_error;
struct my_struct
{
int age;
char *name;
int order_count;
};
int someCond = 1;
//Let's start with a simple case, where we know the type of the pointer being passed (an int)
//If int_out is NULL, then this function will invoke undefined behavior (probably a
//runtime crash, but don't rely on it).
my_error assign_int(int *int_out)
{
if(someCond)
*int_out = 5;
else
*int_out = 38;
return ERROR_NONE;
}
//Need to use a 'double pointer', so that this function is actually changing the pointer
//that exists in the parent scope
my_error dynamically_assign_value_to_pointer(void **pointer)
{
//A pointer internal to this function just to simplify syntax
void *working_ptr = NULL;
if(someCond)
{
//Allocate a region of memory, and store its location in working_ptr
working_ptr = malloc(sizeof(int));
//store the value 12 at the location that working_ptr points to (using '*' to dereference)
*((int *) working_ptr) = 12;
}
else
{
//Allocate a region of memory, and store its location in working_ptr
working_ptr = malloc(sizeof(struct my_struct));
//Fill the struct with data by casting (You can't dereference a void pointer,
//as the compiler doesn't know what it is.)
((struct my_struct *) working_ptr)->age = 22;
((struct my_struct *) working_ptr)->name = "Peter";
((struct my_struct *) working_ptr)->order_count = 6;
}
//Set the pointer passed as an argument to point to this data, by setting the
//once-dereferenced value
*pointer = working_ptr;
return ERROR_NONE;
}
int main (int argc, char *argv[])
{
int an_int;
void *some_data;
assign_int(&an_int);
//an_int is now either 5 or 38
dynamically_assign_value_to_pointer(&some_data);
//some_data now points to either an integer OR a my_struct instance. You will need
//some way to track this, otherwise the data is useless.
//If you get this wrong, the data will be interpreted as the wrong type, and the
//severity of the issue depends what you do with it.
//For instance, if you KNOW FOR SURE that the pointer contains the int, you could
//print it by:
printf("%d", *((int *) some_data));
//And because it is dynamically allocated, you MUST free it.
free(some_data);
return 0;
}
In practice, this is useful for queues, for instance, so you can write a generic queue function and then have different queues for different data types. This is partial code, so won't compile and is a bad idea in this limited case, when a type-safe alternative would be trivial to design, but hopefully you get the idea:
extern my_queue_type myIntQueue;
extern my_queue_type myStructQueue;
my_error get_from_queue(void *data_out, my_queue_type queue_in);
int main (int argc, char *argv[])
{
//...
int current_int;
struct my_struct current_struct;
get_from_queue(&current_int, myIntQueue);
get_from_queue(&current_struct, myStructQueue);
//...
}
Or if you really want to store lots of different types together, you should at least track the type along with the pointer in a struct, so you can use a 'switch' in order to cast and handle logic appropriately when necessary. Again, partial example so won't compile.
enum my_types
{
MY_INTEGER, MY_DOUBLE, MY_STRUCT
};
struct my_typed_void
{
void *data;
enum my_types datatype;
};
my_error get_dynamic_from_global_queue(struct my_typed_void *data_out)
{
//...
data_out->data = malloc(sizeof int);
*((int *)(data_out->data)) = 33;
data_out->datatype = MY_INTEGER;
//...
}
int main (int argc, char *argv[])
{
struct my_typed_void current;
if(get_dynamic_from_global_queue(&current) == ERROR_NONE)
{
switch(current.datatype)
{
//...
case MY_INTEGER:
printf("%d", *((int *) current.data));
break;
//...
}
free(current.data);
}
return 0;
}
Either return the pointer or pass a pointer to pointer (the function then will change the pointer):
void* f1(void* p)
{
p = whatever(p, conditions);
return p;
}
void f2(void** p)
{
*p = whatever(*p, conditions);
}
void assign_value_to_pointer(int** pointer) {
**pointer = 20;
}
void main() {
void* pointer = NULL;
pointer=malloc(sizeof(int));
*(int *)pointer=10;
assign_value_to_pointer(&pointer);
}
I'm not 100% sure what you are looking for, but could it be something like this:
enum pointer_type{INTEGER, STRUCTURE_1, STRUCTURE_2, INVALID};
int assign_value_to_pointer(void ** ptr)
{
uint8_t cond = getCondition();
switch(cond)
{
case 1:
*ptr = (void*) 10;
return INTEGER;
case 2:
*ptr = (void*) someStructOfType1;
return STRUCTURE_1;
case 3:
*ptr = (void*) someStructOfType2;
return STRUCTURE_2;
default:
*ptr = NULL;
return INVALID;
};
}
void main(void)
{
void * ptr = NULL;
int ptrType = assign_value_to_pointer(&ptr);
switch(ptrType)
{
case INTEGER:
assert(ptr == (void*)10);
break;
case STRUCTURE_1:
assert( ((structType1*) ptr)->thing == something);
break;
case STRUCTURE_2:
assert( ((structType2*) ptr)->something == something);
break;
default:
assert(ptr == NULL);
}
}
You can actually type cast the pointer in main() according to the case (condition) and use. However, in my opinion, you can use a union for this purpose.
Create a union with all possible data types.
typedef union _my_union_type_ {
int intVal;
char* stringVal;
bool boolVal;
SomestructType somestruct;//Assuming you need a structure not structure pointer.
void* voidPtrType;
} my_union_type;
Now in main(), create variable of this union type and pass the address of the union to the function.
main() {
my_union_type my_union;
memset(&my_union, 0x00, sizeof(my_union));
assign_value_to_pointer(&my_union);
if (cond1) {
assert(my_union.intVal == 10);
} else if (cond2) {
assert(strcmp(my_union.stringVal, "foo")); //String comparison can not be done using '=='
} else if (cond3) {
assert(my_union.boolVal == true);
} else if (cond4) {
assert(memcmp(&my_union.somestruct, &somestruct, sizeof(somestruct)); //Assuming structure not structure pointer.
} else if (cond5) {
assert(my_union.voidPtrType == NULL);
} else if (cond5) {
//Check my_union.voidPtrType
}
}
And in assign_value_to_pointer, you can store the required value in union variable.
assign_value_to_pointer(my_union_type* my_union) {
if (cond1) {
my_union->intVal = 10;
} else if (cond2) {
my_union->stringVal = "foo";
} else if (cond3) {
my_union->boolVal = true;
} else if (cond4) {
memcpy(&(my_union->somestruct), &somestruct, sizeof(somestruct));
} else if (cond5) {
my_union->voidPtrType = NULL;
} else if (cond6) {
// unknown type!
my_union->voidPtrType = flexiblearraymember.items[index];
}
}
I would like to use this to implement stuff like passing in a NULL error object to a function, and if there is an error, it sets the pointer of the error to some error code, etc.
From the above quote and from the code in the question, it seems you are looking for a variable that can "hold" different types, i.e. sometimes you want it to be an integer, at other times a float, at other times a string and so on. This is called a variant in some languages but variants doesn't exist in C. (see this https://en.wikipedia.org/wiki/Variant_type for more about variants)
So in C you'll have to code your own variant type. There are several ways to do that. I'll give examples below.
But first a few words on pointers in C because the code in the question seem to reveal a misunderstanding as it assigns values directly to the pointer, e.g. pointer = somestruct; which is illegal.
In C is very important to understand the difference between the "value of a pointer" and the "value of the pointed to object". The first, i.e. value of a pointer, tells where the pointer is pointing, i.e. the value of a pointer is the address of the pointed to object. Assignments to a pointer changes where the pointer is pointing. To change the value of the pointed to object, the pointer must be dereferenced first. Example (pseudo code):
pointer = &some_int; // Make pointer point to some_int
*pointer = 10; // Change the value of the pointed to object, i.e. some_int
// Notice the * in front of pointer - it's the dereference
// that tells you want to operate on the "pointed to object"
pointer = 10; // Change the value of the pointer, i.e. where it points to
// In other words, pointer no longer points to some_int
Now back to the "variant" implementation. As already mentioned there are several ways to code that in C.
From your question it seems that you want to use a void-pointer. It's doable and I'll start by showing an example using void-pointer and after that an example using a union.
It's not clear in your question what cond are so in my examples I'll just assume it's a command line argument and I just added some interpretation in order to have a running example.
The common pattern for the examples is the use of a "tag". That is an extra variable that tells the current type of objects value (aka meta-data). So the general variant data type looks like:
struct my_variant
{
TagType tag; // Tells the current type of the value object
ValueType value; // The actual value. ValueType is a type that allows
// storing different object types, e.g. a void-pointer or a union
}
Example 1 : void-pointer and casts
The example below will use a void-pointer to point to the object containing the real value. A value that sometimes is an integer, sometimes a float or whatever is needed. When working with a void-pointer, it's necessary to cast the void-pointer before dereferencing the pointer (i.e. before accessing the pointed to object). The tag field tells the type of the pointed to object and thereby also how the cast shall be.
#include <stdio.h>
#include <stdlib.h>
// This is the TAG type.
// To keep the example short it only has int and float but more can
// be added using the same pattern
typedef enum
{
INT_ERROR_TYPE,
FLOAT_ERROR_TYPE,
UNKNOWN_ERROR_TYPE,
} error_type_e;
// This is the variant type
typedef struct
{
error_type_e tag; // The tag tells the type of the object pointed to by value_ptr
void* value_ptr; // void pointer to error value
} error_object_t;
// This function evaluates the error and (if needed)
// creates an error object (i.e. the variant) and
// assigns appropriate values of different types
error_object_t* get_error_object(int err)
{
if (err >= 0)
{
// No error
return NULL;
}
// Allocate the variant
error_object_t* result_ptr = malloc(sizeof *result_ptr);
// Set tag value
// Allocate value object
// Set value of value object
if (err > -100) // -99 .. -1 is INT error type
{
result_ptr->tag = INT_ERROR_TYPE;
result_ptr->value_ptr = malloc(sizeof(int));
*(int*)result_ptr->value_ptr = 42;
}
else if (err > -200) // -199 .. -100 is FLOAT error type
{
result_ptr->tag = FLOAT_ERROR_TYPE;
result_ptr->value_ptr = malloc(sizeof(float));
*(float*)result_ptr->value_ptr = 42.42;
}
else
{
result_ptr->tag = UNKNOWN_ERROR_TYPE;
result_ptr->value_ptr = NULL;
}
return result_ptr;
}
int main(int argc, char* argv[])
{
if (argc < 2) {printf("Missing arg\n"); exit(1);}
int err = atoi(argv[1]); // Convert cmd line arg to int
error_object_t* err_ptr = get_error_object(err);
if (err_ptr == NULL)
{
// No error
// ... add "normal" code here - for now just print a message
printf("No error\n");
}
else
{
// Error
// ... add error handler here - for now just print a message
switch(err_ptr->tag)
{
case INT_ERROR_TYPE:
printf("Error type INT, value %d\n", *(int*)err_ptr->value_ptr);
break;
case FLOAT_ERROR_TYPE:
printf("Error type FLOAT, value %f\n", *(float*)err_ptr->value_ptr);
break;
default:
printf("Error type UNKNOWN, no value to print\n");
break;
}
free(err_ptr->value_ptr);
free(err_ptr);
}
return 0;
}
Some examples of running this program:
> ./prog 5
No error
> ./prog -5
Error type INT, value 42
> ./prog -105
Error type FLOAT, value 42.419998
> ./prog -205
Error type UNKNOWN, no value to print
As the example above shows, you can implement a variant type using void-pointer. However, the code requires a lot of casting which makes the code hard to read. In general I'll not recommend this approach unless you have some special requirements that forces the use of void-pointer.
Example 2 : pointer to union
As explained earlier C doesn't have variants as they are known in other languages. However, C has something that is pretty close. That is unions. A union can hold different types at different times - all it misses is a tag. So instead of using a tag and a void-pointer, you can use a tag and a union. The benefit is that 1) casting will not be needed and 2) a malloc is avoided. Example:
#include <stdio.h>
#include <stdlib.h>
typedef enum
{
INT_ERROR_TYPE,
FLOAT_ERROR_TYPE,
UNKNOWN_ERROR_TYPE,
} error_type_e;
// The union that can hold an int or a float as needed
typedef union
{
int n;
float f;
} error_union_t;
typedef struct
{
error_type_e tag; // The tag tells the current union use
error_union_t value; // Union of error values
} error_object_t;
error_object_t* get_error_object(int err)
{
if (err >= 0)
{
// No error
return NULL;
}
error_object_t* result_ptr = malloc(sizeof *result_ptr);
if (err > -100) // -99 .. -1 is INT error type
{
result_ptr->tag = INT_ERROR_TYPE;
result_ptr->value.n = 42;
}
else if (err > -200) // -199 .. -100 is FLOAT error type
{
result_ptr->tag = FLOAT_ERROR_TYPE;
result_ptr->value.f = 42.42;
}
else
{
result_ptr->tag = UNKNOWN_ERROR_TYPE;
}
return result_ptr;
}
int main(int argc, char* argv[])
{
if (argc < 2) {printf("Missing arg\n"); exit(1);}
int err = atoi(argv[1]); // Convert cmd line arg to int
error_object_t* err_ptr = get_error_object(err);
if (err_ptr == NULL)
{
// No error
// ... add "normal" code here - for now just print a message
printf("No error\n");
}
else
{
// Error
// ... add error handler here - for now just print a message
switch(err_ptr->tag)
{
case INT_ERROR_TYPE:
printf("Error type INT, value %d\n", err_ptr->value.n);
break;
case FLOAT_ERROR_TYPE:
printf("Error type FLOAT, value %f\n", err_ptr->value.f);
break;
default:
printf("Error type UNKNOWN, no value to print\n");
break;
}
free(err_ptr);
}
return 0;
}
In my opinion this code is easier to read than the code using void-pointer.
Example 3 : union - no pointer - no malloc
Even if example 2 is better than example 1 there is still dynamic memory allocation in example 2. Dynamic allocation is part of most C programs but it is something that shall be used only when really needed. In other words - objects with automatic storage duration (aka local variables) shall be prefered over dynamic allocated objects when possible.
The example below shows how the dynamic allocation can be avoided.
#include <stdio.h>
#include <stdlib.h>
typedef enum
{
NO_ERROR,
INT_ERROR_TYPE,
FLOAT_ERROR_TYPE,
UNKNOWN_ERROR_TYPE,
} error_type_e;
typedef union
{
int n;
float f;
} error_union_t;
typedef struct
{
error_type_e tag; // The tag tells the current union usevalue_ptr
error_union_t value; // Union of error values
} error_object_t;
error_object_t get_error_object(int err)
{
error_object_t result_obj;
if (err >= 0)
{
// No error
result_obj.tag = NO_ERROR;
}
else if (err > -100) // -99 .. -1 is INT error type
{
result_obj.tag = INT_ERROR_TYPE;
result_obj.value.n = 42;
}
else if (err > -200) // -199 .. -100 is FLOAT error type
{
result_obj.tag = FLOAT_ERROR_TYPE;
result_obj.value.f = 42.42;
}
else
{
result_obj.tag = UNKNOWN_ERROR_TYPE;
}
return result_obj;
}
int main(int argc, char* argv[])
{
if (argc < 2) {printf("Missing arg\n"); exit(1);}
int err = atoi(argv[1]); // Convert cmd line arg to int
error_object_t err_obj = get_error_object(err);
switch(err_obj.tag)
{
case NO_ERROR:
printf("No error\n");
break;
case INT_ERROR_TYPE:
printf("Error type INT, value %d\n", err_obj.value.n);
break;
case FLOAT_ERROR_TYPE:
printf("Error type FLOAT, value %f\n", err_obj.value.f);
break;
default:
printf("Error type UNKNOWN, no value to print\n");
break;
}
return 0;
}
Summary
There are many ways of solving the problem addressed by OP. Three examples have been given in this answer. In my opinion example 3 is the best approach as it avoids dynamic memory allocation and pointers but there may be situations where example 1 or 2 is better.
You are not far from success, you just miss an asterisk to dereference the argument:
void assign_value_to_pointer(void* pointer) {
if (cond1) {
*pointer = 10; // note the asterisk
...
}
void main() {
void* pointer = NULL;
assign_value_to_pointer(&pointer);
}
In C language, arguments to functions are always passed by value. If you want the function to modify the argument, you must pass the address of the variable you want to modify. In main(), you are doing that - correct. The called function can write where its argument points to, hence modifying the original variable; to do this, you must dereference the argument.
The compiler should get angry on the assignment, because it does not know how many bytes to write (I'm keeping it simple). So, you have to say what kind of object the pointer points to, like this:
*(int *) pointer = 10;
The typecast you choose is up to you, it depends on the context.
At this point... why not declare differently the function:
void assign_value_to_pointer(int* pointer) {
if (cond1) {
*pointer = 10; // note the asterisk
}
Now the typecast is no more necessary because the compiler knows the kind of object (again I am keeping it simple - void is quite special).
******* EDIT after comments
Well, I am not a guru in C language and, besides, I wanted to keep a low profile to better help the OP.
For simple cases, the right declaration is naive. The typecast can be more flexible because the function can have several assignment statements to choose from depending on context. Lastly, if the function is passed the pointer and some other parameter, everything is possible, including using memcpy(). But this last solution opens up a world...
To reply to Lance (comment below): well, I think that there is no way to do an assignment if you don't know the type of object you are writing to. It seems a contracdition to me...

C: Stack element overwritten by a function call

I'm doing a school assignment, I've I've run into 2 problems. I have to simulate stacks, with arrays.
My current code is as follows:
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int capacity;
int * array;
int size;
} stack_tt;
int pop(stack_tt * stack_p);
void push(stack_tt * stack_p, int value);
int top(stack_tt * stack_p);
stack_tt * newStack(void);
int empty(stack_tt * stack_p);
int main() {
stack_tt * myStack = newStack();
push(myStack, 123);
push(myStack, 99);
push(myStack, 4444);
while (!empty(myStack)) {
int value;
value = pop(myStack);
printf("popped: %d\n", value);
}
return 0; }
stack_tt * newStack(){
stack_tt * newS = malloc(sizeof(stack_tt) * 20);
(*newS).capacity = 1;
(*newS).size = 0;
return newS;
}
void push(stack_tt * stack_p, int value){
if ((*stack_p).size >= (*stack_p).capacity) {
(*stack_p).capacity*=2;
//realloc(stack_p, stack_p->capacity * sizeof(stack_tt));
}
(*stack_p).array = &value;
(*stack_p).size++;
}
int pop(stack_tt * stack_p){
(*stack_p).size--;
int fap = *(*stack_p).array;
return fap;
}
int empty(stack_tt * stack_p){
if ((*stack_p).size >= 1)
return 0;
return 1;
}
Fist of, when I call the line
while(!empty(myStack))
It changes the value in my array to 1.
secondly I'm not able to change individual values in my array, whenever I try things like:
(*stack_p).array[0] = value;
It doesn't know where in the memory to look.
I hope someone is able to help me out :)
There are a couple of problems with the code as I see it.
Lets take the push function where you do
(*stack_p).array = &value;
That will make the array structure member point to the local variable value, and once the function returns the variable cease to exist leaving you with a stray pointer and using that pointer will lead to undefined behavior.
The second problem with that code is that your stack will only be pointing (illegally) to the last element added.
You must allocate memory explicitly for array and use capacity to keep track of how much memory is allocated. The use size as an index into the allocated array for the pushing and popping. Something like
stack_tt * newStack(){
stack_tt * newS = malloc(sizeof(stack_tt)); // Only allocate *one* structure
newS->capacity = 0; // Start with zero capacity
newS->size = 0;
newS->array = NULL;
return newS;
}
void push(stack_tt * stack_p, int value){
if (stack_p->size + 1 > stack_p->capacity){
// Increase capacity by ten elements
int new_capacity = stack_p->capacity + 10;
int * temp_array = realloc(stack_p->array, new_capacity * sizeof(int));
if (temp_srray == NULL)
return;
stack_p->capacity = new_capacity;
stack_p->array = temp_array;
}
stack_p->array[stack_p->size++] = value;
}
int pop(stack_tt * stack_p){
if (stack_p->size > 0)
return stack_p->array[--stack_p->size];
return 0;
}
int empty(stack_tt * stack_p){
return stack_p->size == 0;
}
There is no need to allocate space for 20 structs of type stack_tt, you only need to allocate space for one:
stack_tt * newS = malloc(sizeof(stack_tt));
however you need to allocate space for elements of the struct member array:
newS->array = malloc( sizeof(int)*20);
newS->size = 0;
newS->capacity = 20;
now you can use the array member.
When you push a value to the 'stack', you shouldn't overwrite the array member with the address of the local variable, that doesn't make sense and will cause undefined behavior in addition of loosing the previously allocated memory. Instead simply assign the value to the member array, in the function push:
stack_p->array[stack_p->size] = value;
stack_p->size++;
Similarly when you pop an element, take the current element from the member array:
stack_p->size--;
int fap = stack_p->array[stack_p->size];
The rest of the functions and code should be fixed in the same manner.
You're code is good, but probably you didn't understand the usage of realloc:
//realloc(stack_p, stack_p->capacity * sizeof(stack_tt));
This function returns a pointer to the newly allocated memory, or NULL if the request fails.
The realloc (as the function suggests) takes the memory pointed by the pointer you pass, and copies that memory block in a new and resized block. So the right code should be.
stack_p->array = realloc(stack_p->array, stack_p->capacity * sizeof(stack_tt));
This other line is wrong:
(*stack_p).array = &value;
Change it with:
stack_p->array[stack_p->size] = value;
Another little suggestion, every (*stack_p). can be replaced by stack_p->, which is more elegant.
In the newStack() you're mallocing 20 structs which is kinda useless. You just need one.
Then you should malloc the array for the first time:
newS->array = malloc(sizeof(int));
newS->capacity = 1;

C Pointer and Memory Allocation: Realloc Arrays and Pointer Passing

For those experienced with C, this will be a simple memory allocation/referencing problem:
Here are my data structures:
struct configsection {
char *name;
unsigned int numopts;
configoption *options;
};
typedef struct configsection configsection;
struct configfile {
unsigned int numsections;
configsection *sections;
};
typedef struct configfile configfile;
Here are my routines for initializing a configsection or configfile, and for adding a configsection to a configfile:
// Initialize a configfile structure (0 sections)
void init_file(configfile *cf) {
cf = malloc(sizeof(configfile));
cf->numsections = 0;
}
// Initialize a configsection structure with a name (and 0 options)
void init_sec(configsection *sec, char *name) {
sec = malloc(sizeof(configsection));
sec->numopts = 0;
sec->name = name;
printf("%s\n", sec->name);
}
// Add a section to a configfile
void add_sec(configfile *cf, configsection *sec) {
// Increase the size indicator by 1
cf->numsections = cf->numsections + 1;
// Reallocate the array to accommodate one more item
cf->sections = realloc(cf->sections, sizeof(configsection)*cf->numsections);
// Insert the new item
cf->sections[cf->numsections] = *sec;
}
I believe my problem originates in my init_sec() function. Here is an example:
int main(void) {
// Initialize test configfile
configfile *cf;
init_file(cf);
// Initialize test configsections
configsection *testcs1;
init_sec(testcs1, "Test Section 1");
// Try printing the value that should have just been stored
printf("test name = %s\n", testcs1->name);
Although the printf() in init_sec() successfully prints the name I just stored in the configsection, attempting the same thing in the printf() of main() produces a segmentation fault. Further, addsec() produces a segmentation fault.
This routine should be
void init_file(configfile **cf) {
*cf = malloc(sizeof(configfile));
(*cf)->numsections = 0;
(*cf)->sections = NULL; // You forgot to initialise this.
}
i.e. called by init_file(&myconfigfilepointer); so the malloc return value gets passed back.
Need to do the same trick for init_sec
This function is incorrect - here is a corrected version
void add_sec(configfile *cf, configsection *sec) {
// Increase the size indicator by 1
// Reallocate the array to accommodate one more item
cf->sections = realloc(cf->sections, sizeof(configsection)*(1 + cf->numsections));
// Insert the new item
cf->sections[cf->numsections] = *sec; // Since arrays start at 0
cf->numsections = cf->numsections + 1;
}
You then need to adjust the calls in main
At no point do you initialise cf->sections, which means when you try to realloc it the first time, you're passing rubbish. Adding:
cf->sections = NULL;
to init_file should help.
You're also not checking any return codes, but you knew that yes?
You need to pass a pointer of the value to be updated... eg:
// Initialize a configfile structure (0 sections)
void init_file(configfile **cf) {
*cf = malloc(sizeof(configfile));
(*cf)->numsections = 0;
}
configfile *var;
init_file(&var);
printf("%d\n", var->numsections);
Otherwise you are just updating the local pointer *cf and not the original passed in value
You need to really rethink how function arguments are passed in C and what pointers are. Your problem has nothing to do with memory allocation. Rather, your code is assigning a pointer to dynamically allocated memory only to a local variable, of which the calling code knows nothing.
While you could solve the problem by passing a pointer to the caller's pointer (i.e. a double pointer), this is not necessarily the most elegant or most usual way of handling things. Rather, you should return the result of the allocation from the function. While you're at it, you should also use calloc to zero out the memory right away. Wrapping it all up:
typedef struct substuff_
{
int a;
double b;
} substuff;
typedef struct stuff_
{
unsigned int n;
substuff * data;
} stuff;
substuff * init_substuff()
{
substuff * const p = malloc(sizeof *p);
if (p) { p->a = 5; p->b = -0.5; }
return p;
}
stuff * init_stuff()
{
substuff * const p = init_substuff();
if (!p) return NULL;
stuff * const q = malloc(sizeof *q);
if (q) { q->n = 10; q->data = p; }
return q;
}
As an exercise, you should write the corresponding functions void free_substuff(substuff *) and void free_stuff(stuff *).
Yes, there is a problem in init_sec
// Initialize a configsection structure with a name (and 0 options)
void init_sec(configsection *sec, char *name) {
sec = malloc(sizeof(configsection));
sec->numopts = 0;
sec->name = name;
printf("%s\n", sec->name);
}
You're just copying the name pointer here, which means, that it points to the original storage of name. If you'd call init_sec like this
configsection foobar()
{
configsection sec;
char name[80];
get_name(name);
init_sec(sec, name);
return sec;
}
The name pointer became invalid the moment foobar returned. You need to duplicate the string and keep your private copy around. In init_sec:
sec->name = strdup(name);
But there's more. In the very first line of init_sec you're overwriting the pointer that was passed to init_sec with the one of malloc. So the new pointer never gets passed back to the calle. Either use a pointer to a pointer, don't take a configsection pointer at all (after all, you're allocating), but just return the allocated pointer: Complete corrected function:
// Initialize a configsection structure with a name (and 0 options)
configsection* init_sec(char *name) {
configsection *sec = malloc(sizeof(configsection));
sec->numopts = 0;
sec->name = name;
printf("%s\n", sec->name);
return sec;
}

Struct member corrupted after passed but not after passed again

I'm having some very strange bug in my ANSI C program.
I'm using debugger and I've observed that 'size' variable is corrupted in function 'doSthing.' Outside of 'doSthing' 'size' got a proper value, but inside 'doSthing' I've got a value nothing similar to what it should be, possibly some random data. This would be not be such a mystery but...
In 'doAnotherThing' which is called from 'doSthing' I get the proper value again. I suppose if it passes the correct value, it is not corrupted anyway, am I wrong? But then why does it have a different value?
The pointer in struct does not change inside the functions.
Memory is allocated for both oTV and oTV->oT.
I really don't see what's happening here...
typedef struct{
ownType *oT[] /* array of pointers */
int size;
} ownTypeVector;
void doSthing(ownTypeVector* oTV);
void doAnotherThing(ownTypeVector* oTV);
void doSthing(ownTypeVector* oTV)
{
...
doAnotherThing(oTV);
...
}
Thanks for your comments, I collected all the code that contains control logic and data structures so that it compiles. It runs on in an embedded systems, that can receive characters from multiple sources, builds strings from it by given rules and after the strings are ready, calls a function that needs that string. This can also be a list of functions. This is why I have function pointers - I can use the same logic for a bunch of things simply by choosing functions outside the 'activityFromCharacters' function.
Here I build a data structre with them by adding A-s, B-s and C-s to the AVector.
Of course every one of these separate sources has their own static strings so that they do not bother each other.
The problem again in the more detailed version of the code:
'aV->size' has got a proper value everywhere, except 'handleCaGivenWay.' Before it gets calles, 'aV->size' is ok, in 'addA' 'aV->size' is ok, too. After leaving 'handleCaGivenWay' it is ok again.
#define NUMBER_OF_AS 1
#define NUMBER_OF_BS 5
#define NUMBER_OF_CS 10
typedef struct{
char name[81];
} C;
typedef struct{
C *c[NUMBER_OF_CS]; /* array of pointers */
int size;
int index;
} B;
typedef struct{
B *b[NUMBER_OF_BS]; /* array of pointers */
char name[81];
int size;
} A;
typedef struct{
A *a[NUMBER_OF_AS]; /* array of pointers */
int size;
} AVector;
typedef struct {
char *string1;
char *string2;
} stringBundle;
typedef struct{
void (*getCharacter)(char *buffer);
void (*doSthingwithC)(stringBundle* strings,AVector* aV);
AVector* aV;
} functionBundle;
void getCharFromaGivenPort(char *buffer)
{
//...
}
void addA(AVector * aV, stringBundle* strings)
{
aV->a[aV->size]->size = 0;
++aV->size;
int i = 0;
if(strlen(strings->string2) < 81)
{
for(i;i<81;++i)
{
aV->a[aV->size-1]->name[i] = strings->string2[i];
}
}
else {report("Too long name for A:");
report(strings->string2);}
}
void handleCaGivenWay(stringBundle* strings,AVector* aV)
{
A* a;
a = NULL;
if(aV->size) { a = aV->a[aV->size-1]; }
switch(1)
{
case 1: addA(aV,strings); break;
case 2: //addB()...
default: if (a && aV->size)
{ //addC(a->thr[a->size-1],c);
}
else report("A or B or C invalid");
break;
}
//handleCaGivenWay
}
void activityFromCharacters(stringBundle* strings,functionBundle* funcbundle)
{
/* some logic making strings from characters by */
/* looking at certain tokens */
(* funcbundle->doSthingwithC)(strings,funcbundle->aV);
}
//activityFromCharacters
AVector* initializeAVector(void)
{
AVector* aV;
if (NULL == (aV = calloc(1,sizeof(AVector))))
{ report("Cannot allocate memory for aVector."); }
int i = 0;
int j = 0;
int k = 0;
for(i; i < NUMBER_OF_AS; ++i)
{
if (NULL == (aV->a[i] = calloc(1,sizeof(A))))
{ report("Cannot allocate memory for As."); }
aV->a[i]->size = 0;
aV->a[i]->name[0] = 0;
for(j; j < NUMBER_OF_BS; ++j)
{
if (NULL == (aV->a[i]->b[j] = calloc(1,sizeof(B))))
{ report("Cannot allocate memory for Bs."); }
aV->a[i]->b[j]->size = 0;
for(k; k < NUMBER_OF_CS; ++k)
{
if (NULL == (aV->a[i]->b[j]->c[k] = calloc(1,sizeof(C))))
{ report("Cannot allocate memory for Cs."); }
}
}
}
aV->size = 0;
return aV;
//initializeProgramVector
}
int main (void)
{
AVector* aV;
aV = initializeAVector();
while(1)
{
static stringBundle string;
static char str1[81];
static char str2[81];
string.string1 = str1;
string.string2 = str2;
functionBundle funcbundle;
funcbundle.getCharacter = &getCharFromaGivenPort;
funcbundle.doSthingwithC = &handleCaGivenWay;
funcbundle.aV = aV;
activityFromCharacters(&string,&funcbundle);
}
//main
}
your code shows that it hasn't any error...
But i think you are doing mistake in getting the value of size in doSthing function.
you are printing there its address. so concentrate on some pointer stuff..
Try printing the oTV->size just before the call and as the first statement in doSthing function. If you get the correct value in both print, then the problem is with the function doSthing. Problem could be better understood if you've shown the code that calls doSthing.
Searched a long time to find this. I found 2 problems, but dont know what exactly you are trying to accomplish so i cannot tell for certain that the fix'es i propose are what you intend.
typedef struct{
A *a[NUMBER_OF_AS]; /* array of pointers */
int size;
} AVector;
// and in addA():
aV->a[aV->size]->size = 0;
First: You are inlining the array of pointers in the struct. What i think what you want and need is a pointer to a pointer array so that it can grow which is what you want in addA() i think. The line from addA() aV->a[aV->size]->size = 0; does not communicate your intention very well but it looks like you are trying to change the value beyond the last entry in the array and since it is inlined in the struct it would result to the separate field size by pure coincidence on some alignments; this is a very fragile way of programming. So what i propose is this. Change the struct to contain A** a; // pointer to pointer-array, malloc it initially and re-malloc (and copy) it whenever you need it to grow (in addA()).

C - Passing a Pointer to a Function and then Passing that Same Pointer Inside the Function to Another Function

Whew! Long title...here's some pseudo-code to explain that verbiage:
int main(){
int* ptr = function1(); //the data that ptr points to is correct here
function2(ptr);
}
int function2(int* ptr){
//the data that ptr points to is still correct
int i;
for(i=0;i<length;printf("%d\n", (*ptr)[i]), i++); //since ptr points to a contiguous block of memory
function3(ptr);
}
int function3(int* ptr){
//the data that ptr points to is INCORRECT!!!
}
Why would the data in function3 be incorrect?
Note: function1 performs a malloc() and returns the pointer to that memory.
ACTUAL CODE
#include <stdlib.h>
#include <stdio.h>
//Structures
struct hash_table_data_
{
int key, data;
struct hash_table_data_ *next, *prev;
};
struct hash_table_
{
int num_entries;
struct hash_table_data_ **entries;
};
typedef struct hash_table_data_ hash_table_data;
typedef struct hash_table_ hash_table;
//Prototypes
hash_table *new_hash_table(int num_entries);
int hash_table_add(hash_table *ht, int key, int data);
int hash_table_loader(hash_table* ht);
//Main
int main()
{
int num_entries = 8;//THIS MUST BE AUTOMATED
hash_table* ht = new_hash_table(num_entries);
hash_table_loader(ht);
return 0;
}
//Function Definitions
hash_table *new_hash_table(int num_entries)
{
hash_table* ht = (hash_table*) malloc(sizeof(hash_table));
hash_table_data* array = malloc(num_entries * sizeof(hash_table_data));
int i;
for (i=0;i<num_entries;i++)
{
array[i].key = -1;
array[i].data = -1;
array[i].next = NULL;
array[i].prev = NULL;
}
ht->entries = &array;
ht->num_entries = num_entries;
return ht;
}
int hash_table_add(hash_table *ht, int key, int data)
{
//VERIFY THAT THE VALUE ISN'T ALREADY IN THE TABLE!!!!!!!!!!!
int num_entries = ht->num_entries;
hash_table_data* array = *(ht->entries); //array elements are the LL base
int hash_val = key%num_entries;
printf("adding an element now...\n");
printf("current key: %d\n", array[hash_val].key);
int i;
for(i=0;i<num_entries;printf("%d\n", (*(ht->entries))[i].key),i++);//DATA IS INCORRECT!!!!
if (array[hash_val].key == -1)//is this the base link?
{
printf("added a new base link!\n");
array[hash_val].key = key;
array[hash_val].data = data;
array[hash_val].next = NULL;
array[hash_val].prev = &(array[hash_val]);
}
else//since it's not the base link...do stuff
{
hash_table_data* new_link = malloc(sizeof(hash_table_data));
new_link->key = key;//set the key value
new_link->data = data;//set the data value
if (array[hash_val].next == NULL)//we must have the second link
{
printf("added a new second link!\n");
new_link->prev = &(array[hash_val]); //set the new link's previous to be the base link
array[hash_val].next = new_link; //set the first link's next
}
else//we have the 3rd or greater link
{
printf("added a new 3rd or greater link!\n");
hash_table_data next_link_val = *(array[hash_val].next);
while (next_link_val.next != NULL)//follow the links until we reach the last link
{
next_link_val = *(next_link_val.next);//follow the current link to the next
}
//now that we've reached the last link, link it to the new_link
next_link_val.next = new_link; //link the last link to the new link
new_link->prev = &(next_link_val); //link the new link to the last link
}
}
return 0;
}
int hash_table_loader(hash_table* ht)
{
int i;
for(i=0;i<(ht->num_entries);printf("%d\n", (*(ht->entries))[i].key),i++); //DATA IS STILL CORRECT HERE
FILE *infile;
infile = fopen("input.txt", "r");
while(!feof(infile))
{
int key,data;
fscanf(infile, "%d %d", &key, &data);
hash_table_add(ht, key, data);
}
fclose(infile);
}
Note: Issue occurring the first time hash_table_add() is called.
Your first problem is here:
ht->entries = &array;
You cause the structure to hold a hash_table_data** which points to the variable hash_table_data* array which is local to the function; then you exit the function and return a pointer to the structure. The structure still exists (it was allocated via malloc(), and the stuff that array points to still exists, but array itself does not. Accordingly, this pointer within the structure is now invalid.
As far as I can tell, there is no reason for you to be holding a pointer-to-pointer here. Just use hash_table_data* as the entries type, and copy array into that struct member. Pointers are values too.
I guess you iterate incorrectly
for(i=0;i<length;printf("%d\n", (*ptr)[i]), i++);
this is nonsense.
You should rewrite it as this:
for(i=0;i<length;i++)
printf("%d\n", ptr[i]);
(*ptr)[i] is just wrong, it doesn't make sense if you think about it.
*ptr is the first element of the pointed-to array of ints.
ptr[i] is thi ith one, this is what you need.
Please, read Section 6 carefully.
A couple of advises based on this question:
Don't write overcomplicated code like this for statement with comma operator used, it just rarely needed and leads not only to confusion, but to mistakes (although no mistakes with it in this particular example)
Look carefully for mistakes, don't blame everything on functions. If your code doesn't work, try finding the exact place which is wrong and prove it. In this example people who tested your code were right: functions are definitely not the cause of the error.
hash_table *new_hash_table(int num_entries)
{
hash_table* ht = (hash_table*) malloc(sizeof(hash_table));
hash_table_data* array = malloc(num_entries * sizeof(hash_table_data));
// ....
ht->entries = &array; // Problem
// ...
return ht;
} // Life time of array ends at this point.
You are taking the reference of the local variable array and assigning it to ht->entries which is no more valid once the function returns.

Resources