I have pointers in main for which I don't know it's size. A function returns this pointer to main. Inside the function I can calulate the size of pointer and hence need to store values in them and return them to main. How to modify/allocate memory in this case.
int main()
{
int *row_value, *col_value;
col_row_value(row_value,col_value);
...
return(0);
}
void col_row_value(row_value,col_value)
{
// how to allocate/modify memory for row_value and col_value and store data
// for example would like to allocate memory here
int i;
for(i=0;i<10;i++) {
row_value[i]=i;
col_value[i]=i;
}
}
I tried something like this,it doesn't work
int main()
{
int *row_value, *col_value;
row_value=NULL;
col_value=NULL;
col_row_value(&row_value,&col_value);
...
return(0);
}
void col_row_value(int **row_value,int **col_value)
{
// how to allocate/modify memory for row_value and col_value and store data
// for example would like to allocate memory here
int i;
*row_value=(int*)realloc(*row_value,10*sizeof(int));
*col_value=(int*)realloc(*col_value,10*sizeof(int));
for(i=0;i<10;i++) {
row_value[i]=i;
col_value[i]=i;
}
}
This:
*row_value=(int*)realloc(row_value*,10*sizeof(int));
should be:
*row_value = realloc(*row_value,10*sizeof(int));
/** ^ **/
Note the cast is unnecessary. Assign the result of realloc() to a temporary pointer in case the reallocation fails which would mean the original memory would be inaccessible.
int* tmp = realloc(*row_value, 10 * sizeof(*tmp));
if (tmp)
{
*row_value = tmp;
}
Note the for loop does not assign a value to the first element in row_value or col_value:
for(i=1;i<10;i++)
as it starts at index 1 and the assignments within the for should be:
(*row_value)[i] = i;
(*col_value)[i] = i;
The second version is essentially correct.
You need to say:
realloc(*row_value, 10 * sizeof(int));
// ^^^
Mind the star!
If it helps, rename your function arguments to:
col_row_value(int ** ptr_to_row_ptr, int ** ptr_to_col_ptr);
That way, you won't confuse yourself as much.
Related
I'm working in C.
I have a simple struct named Entity
typedef struct Entity
{
int x, y;
int velX, velY;
}Entity;
I'm creating a dynamic array of type Entity and size 1. Then I add one element with my addEntity function
void addEntity(Entity** array, int sizeOfArray)
{
Entity* temp = malloc((sizeOfArray + 1) * sizeof(Entity));
memmove(temp, *array, (sizeOfArray)*sizeof(Entity));
free (*array);
*array = temp;
}
Then I use another function to change the values of the two elements :
int main()
{
Entity* entities = malloc(sizeof(Entity)); // dynamic array of size 1
addEntity(&entities, 1); // add one element
changeValue(&entities[0], 10); // change the values of the first two elemebts
changeValue(&entities[1], 20);
printf("%d\n", entities[0].x); // print the values
printf("%d", entities[1].x);
free(entities); // free the memory
return 0;
}
void changeValue(Entity* entity, int nb)
{
entity->x = nb;
}
The result of this is 10 and 20, everything works fine. Now if I use this syntax instead
int main()
{
Entity* entities = malloc(sizeof(Entity)); // dynamic array of size 1
addEntityAndSetValues(entities);
printf("%d\n", entities[0].x); // print the values
printf("%d", entities[1].x);
free(entities); // free the memory
return 0;
}
void addEntityAndSetValues(Entity* entities)
{
addEntity(&entities, 1);
changeValue(&entities[0], 10);
changeValue(&entities[1], 20);
}
I don't get 10 and 20 but some random numbers. I really don't understand why.
Reason is C is pass by value.
When in the second case you pass the pointer - a copy of it is passed to the function. Now when you write &entities it is the address of the local variable. And the variables in main don't see any change - because you didn't change them. So you get garbage value.
To be more clear
void addEntityAndSetValues(Entity* entities)
{
addEntity(&entities, 1); <--- entities is a local variable.
}
Now you add call addEntity:
void addEntity(Entity** array, int sizeOfArray)
{
...
free (*array);
*array = temp; <--- assigning to the local variable the address of the allocated chunk.
}
Then you call the other function to change it's value - those are alright. But when you return from the function then everything in that local variable is gone.
If you do this - then it would work.
In main()
addEntityAndSetValues(&entities);
In addEntityAndSetValues()
void addEntityAndSetValues(Entity** entities)
{
addEntity(entities, 1);
changeValue(&(*entities)[0], 10);
changeValue(&(*entities)[1], 20);
}
Here it worked because you have passed the the address of the variable in main() and then you made changes to that variable - and every change in the value of it reflected.
The following code works fine without the statement d = *dummy; which is a double pointer dereference. However if this line is present, a segmentation fault occurs. Why so?
The code allocates and initializes memory for data structs dynamically. I was trying to simplify access to the returned pointer-to-pointer.
#include <stdlib.h>
#include <stdio.h>
typedef struct s_dummy {
char dummy_number;
} Dummy;
int mock_read_from_external_source() {
return 4;
}
int load_dummies(Dummy** dummies, int* num_of_dummies) {
*num_of_dummies = mock_read_from_external_source();
*dummies = (Dummy*) calloc(*num_of_dummies, sizeof(Dummy));
if (!dummies) {
return 1; // allocation unsuccessful
}
// Iterate dummies and assign their values...
for (int i = 0; i < *num_of_dummies; i++) {
(*dummies + i)->dummy_number = i;
}
return 0;
}
void main() {
Dummy** dummies;
Dummy* d;
int num_of_dummies = 0;
int *p_num_of_dummies = &num_of_dummies;
int err;
err = load_dummies(dummies, p_num_of_dummies);
// Segmentation fault occurs when dummies is dereferenced
d = *dummies;
if (err) {
exit(err);
}
for (int i = 0; i < num_of_dummies; i++) {
printf("Dummy number: %d\n", (*dummies + i)->dummy_number);
}
}
Thanks in advance.
You are getting the fault because of UB, in part caused by trying to use variable objects without memory. dummies, although created as a Dummies **, has never been provided memory. At the very least, your compiler should have warned you about dummies not being initialized in this call:
err = load_dummies(dummies, p_num_of_dummies);
This is easily addressed by simply initializing the variable when it is created:
Dummy** dummies = {0}; //this initialization eliminates compile time warnings
^^^^^
Then come the run-time errors. The first is called a fatal run-time on my system, which means the OS refused to continue because of a serious problem, in this case an attempt to dereference a null pointer in this line:
dummies = (Dummy) calloc(*num_of_dummies, sizeof(Dummy));
Because you created a Dummy ** called dummies, the first step is to create memory for the pointer to pointers dummies, then create memory for the several instances of dummies[i] that will result. Only then can the members of any of them be written to.
Here is one method illustrating how memory can be created for a Dummies pointer to pointers, ( d ) and several Dummies instances ( d[i] ):
Dummy ** loadDummies(int numPointers, int numDummiesPerPointer)
{
int i;
Dummy **d = {0};
d = malloc(numPointers * sizeof(Dummy *));//Create Dummies **
if(!d) return NULL;
for(i=0;i<numPointers;i++)
{ //Now create Dummies *
d[i] = malloc(numDummiesPerPointer*sizeof(Dummy)); //random size for illustration
if(!d[i]) return NULL;
}
return d;
}
In your main function, which by the way should really be prototyped at a minimum as: int main(void){...}, this version of loadDummies could be called like this:
...
Dummies **dummies = loadDummies(4, 80);
if(!dummies) return -1;//ensure allocation of memory worked before using `dummies`.
...
After using this collection of dummies, be sure to free all of them in the reverse order they were created. Free all instances of dummies[0]-dummies[numPointers-1] first, then free the pointer to pointers, dummies
void freeDummies(Dummy **d, int numPointers)
{
int i;
for(i=0;i<numPointers;i++)
{
if(d[i]) free(d[i]);
}
if(d) free(d);
}
Called like this:
freeDummies(dummies, 4);
dummies was never assigned a value, so de-referencing will attempt to reach some random memory which is almost certainly not going to be part of your program's allocated memory. You should have assigned it to &d.
But you don't even need to do that. Just use &d once when you call the function.
Also, if you return the number of dummies allocated instead of 1/0, you can simplify your code. Something like the below (not tested):
#include <stdio.h>
int mock_read_from_external_source() {
return 10;
}
typedef struct Dummy {
int dummy_number;
} Dummy;
int load_dummies(Dummy** dummies) {
int want, i = 0;
if((want = mock_read_from_external_source()) > 0) {
*dummies = (Dummy*) calloc(want, sizeof(Dummy));
if(*dummies) {
// Iterate dummies and assign their values...
for (i = 0; i < want; i++) {
(*dummies)[i].dummy_number = i;
}
}
}
return i;
}
int main() {
Dummy* d = NULL;
int num_of_dummies = load_dummies(&d); // when &d is de-referenced, changes are reflected in d
if(num_of_dummies > 0) {
for (int i = 0; i < num_of_dummies; i++) {
printf("Dummy number: %d\n", d[i].dummy_number);
}
}
if(d) { // clean up
free(d);
}
return 0;
}
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;
As already written at issue#2217, I want to design a function which return a list of oid in the first out param.
Should I:
Return the list of oids as a pointer to pointer?
int git_commit_tree_last_commit_id(git_oid **out, git_repository *repo, const git_commit *commit, char *path)
Or return the list of oids as a pointer to a custom struct?
int git_commit_tree_last_commit_id(git_oid_xx_struct *out, git_repository *repo, const git_commit *commit, char *path)
What is your advice?
The question is, how do you know how many OIDs are in the returned array, and who allocates the underlying memory.
For the first part there are several possibilities,
Return the number in a separate return parameter,
Use a sentinel value to terminate the list.
Return a new struct type, like git_strarray that contains the count and the
raw data.
For the second part, either
the caller can allocate the underlying memory
The function can allocate the memory
the new struct type can manage the memory.
Which path you go down depends upon what you want the code to look like, how much you expect it to be reused, how critical performance is etc.
To start with I'd go with the simplest, which IMO is function returns count and allocates memory.
That means my function would have to look like this:
int get_some_oids_in_an_array(OID** array, int * count, ... ) {
...
*count = number_of_oids;
*array = (OID*)malloc( sizeof(OID)*number_of_oids);
for(i=0; i<number_of_oids; ++i) {
*array[i]=...;
}
...
return 0;
}
/* Example of usage */
void use_get_oids() {
OID* oids;
int n_oids;
int ok = get_some_oids_in_an_array(&oids, &n_oids, ...);
for(i=0; i<n_oids; ++i ) {
... use oids[i] ...
}
free(oids);
}
Note: I'm returning an array of OID, rather than an array of OID*, either is a valid option, and which will work best for you will vary.
If it turned out I was using this kind of pattern often, then would consider switching to the struct route.
int get_some_oids( oidarray * oids, ... ) {
int i;
oidarray_ensure_size(number_of_oids);
for(i=0; i<number_of_oids; ++i) {
oidarray_set_value(i, ...);
}
return 0;
}
typedef struct oidarray {
size_t count;
OID* oids;
};
/* Example of usage */
void use_get_oids() {
oid_array oids = {0};
get_some_oids(&oids);
for(i=0; i<oids.count; ++i) {
... use oids.oids[i] ...
}
oidarray_release(&oids);
}
I'm trying to expand an array of ints on the heap using realloc but the programme is crashing when I use my custom function "ExpandArrayOfInts" but works fine when I write the expander code within main.
Here is the code (file: main.c) with #defines for both approaches.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int ExpandArrayOfInts(int* arrayToExpand, int expandBy, int inArraySize, int* outArraySize);
int main (int argc, char** argv)
{
#if 1//CODE THAT WORKS
int arraySize = 10;
int* arrayDnmc = NULL;
int* arrayDnmcExpndd;
for (int i = 0; i< 10; ++i)
{
arrayDnmcExpndd = (int*)realloc(arrayDnmc, (arraySize + (i * 10)) * sizeof(int));
if (arrayDnmcExpndd != NULL)
{
arrayDnmc = arrayDnmcExpndd;
memset(arrayDnmc, 0, (arraySize + (i * 10)) * sizeof(int));
}
else
{
printf("Failed to (re)alloc memory for arrayDnmc!\n");
free(arrayDnmc);
return -1;
}
}
free(arrayDnmc);
#else //CODE THAT DOESN'T WORK (Which I'm trying to make it work)
int maxSize = 100;
int arraySize = 10;
int* arrayDnmc = NULL;
arrayDnmc = (int*)malloc(arraySize * sizeof(int));
if (arrayDnmc != NULL)
{
memset(arrayDnmc, 0, arraySize * sizeof(int));
}
else
{
printf("malloc failure!\n");
return -1;
}
while (arraySize < maxSize)
{
if (0 != ExpandArrayOfInts(arrayDnmc, 5, arraySize, &arraySize))
{
printf("Something went wrong.\n");
break;
}
//do something with the new array
printf("new size: %i\n", arraySize);
}
free(arrayDnmc);
#endif
return 0;
}
int ExpandArrayOfInts(int* arrayToExpand, int expandBy, int inArraySize, int* outArraySize)
{
int newSize = inArraySize + expandBy;
int* arrayTemp = (int*)realloc(arrayToExpand, newSize * sizeof(int));
if (arrayTemp != NULL)
{
arrayToExpand = arrayTemp;
*outArraySize = newSize;
return 0;
}
return -1;
}
The part that doesn't work gives the following output:
new size: 15
new size: 20
and then I get the crash message:
"Windows has triggered a breakpoint in c_cplusplus_mixing.exe.
This may be due to a corruption of the heap, which indicates a bug in c_cplusplus_mixing.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while c_cplusplus_mixing.exe has focus.
The output window may have more diagnostic information."
The call stack doesn't seem very meaningful (at least for a novice like myself).
Call Stack:
ntdll.dll!775c542c()
[Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll]
ntdll.dll!7758fdd0()
ntdll.dll!7755b3fc()
Note, I'm using visual studio 2008 and running Debug build. (Release doesn't work either).
Could anyone please point me to where I'm going wrong! and please let me know if more details are needed.
Many thanks in advance,
Hasan.
The problem is that ExpandArrayOfInts is receiving a pointer to an int instead of a pointer to the pointer that has to reallocate. It should look like this:
int ExpandArrayOfInts(int** arrayToExpand, int expandBy, int inArraySize, int* outArraySize)
and then you would call it like this:
ExpandArrayOfInts(&arrayDnmc, 5, arraySize, &arraySize))
I'd recommend you to look for questions related to pointers in stackoverflow so that you get a better understanding of them.
From the realloc() documentation on my system:
realloc() returns a pointer to the
newly allocated memory, which is
suitably aligned for any kind of
variable and may be different from
ptr, or NULL if the request fails.
Your ExpandArrayOfInts() declaration and implementation does not allow realloc to modify the actual pointer in main() - it implicitly assumes that its value cannot change. When realloc() moves the memory area and does return a different pointer, it calls free() on the pointer it was called with. The rest of your program, though, goes on using the original value which is now invalid, hence the crash.
You should use a pointer-to-a-pointer to pass the memory area pointer by reference, instead:
int ExpandArrayOfInts(int** arrayToExpand, int expandBy, int inArraySize, int* outArraySize)
.
.
.
*arrayToExpand = (int*)realloc(*arrayToExpand, newSize * sizeof(int));