I am making a struct with undefined size.
#define namemax 128
struct Image{
char name[namemax+1];
int length;
double *array; //double array[256]
};
struct Image* graph;
graph=malloc(max*sizeof(struct Image));
If I define array[256], everything work fine.
but if I use double *array, and then write
graph[check].array = malloc( 100 * sizeof(double *));
it creates a segment fault.
I was wondering how can I define the size using malloc and realloc for array.
If I add value in the array, it shows segment fault.
struct Image* graph;//outside the while loop
while: //it is inside the while loop
//basically it read different name each line, and put the x and y to the array
graph[check].array = malloc( 100 * sizeof(double));
check++;
strcpy( graph[check].name,type);
graph[check].array[count]=shiftX;
graph[check].array[count+1]=shiftY;
That because double * array is declaring a pointer to an array, not storage. You want to declare storage here. The easiest way is to simply define the array as double array[1] and make sure it's the last element in the struct. You can then allocate space for the structure using malloc() and realloc() by passing them the size of the base struct plus the size of the array (sizeof double * the number of array elements).
One problem I see is using sizeof(double *) instead of sizeof(double) even if both are the same if you're using x86-64 architecture.
i think it makes seg fault because in malloc you have said sizeof(double *) (Actually you declare an array of array).
Just try to say sizeof(double) it may work but I dont know that for sure because I haven't tested it.
And by the way when you declare array staticly you reserve space for it when you declare your struct variable but when you declare it as pointer ( dynamic array ) you should reserve space for it and you can change the array's size. You should use realloc google it.
Related
In my program I have a structure that looks like this:
struct structure {
int n;
int *arr;
};
And I allocate memory for arr like this:
structure->arr = malloc(sizeof(int) * arr_size);
Now here is where I start to get confused, and I am not sure if I am doing it right. What I want to do is use "arr" as an array to store or access integers. So I set arr to point to an array that I created and filled with 0's:
int new_arr[i];
structure.arr = new_arr;
I am not sure if this is right, but so far I don't get any errors. So I create another array that stores these structures, and I insert some new structures in it. But when I try to free the member arr from any of the structures inside the array (like this free(&array_of_struct[i].arr);) I get an error:
==747==ERROR: AddressSanitizer: attempting free on address which was not malloc()-ed: 0x7fffd7c6ad08 in thread T0
SUMMARY: AddressSanitizer: bad-free (/lib/x86_64-linux-gnu/libasan.so.5+0x10d7cf) in __interceptor_free
==747==ABORTING
So I think I understand what the problem is, but I have no idea how to solve it. I don't imagine this is the way I'm supposed to point to an array, so can anyone tell me how to do it right?
UPDATE
So instead of writing "structure.arr = new_arr" I am now using memset this way:
memset(structure.arr, '\0', array_size * sizeof(int));
But I still get the same arror when trying to free structure.arr. Also if I try to use mempcy. Could there be something wrong with free(&array_of_struct[i].arr)?
UPDATE2
So I actually managed to use mempcy and free member "arr". The problem is, that I can only do it before I append the structure to my array of structures. If I try to free it after that (as a member of the array) I get the errors.
LAST UPDATE
I have managed to make it work with memset. The problem was that I had to write free(array_of_struct[i].arr) instead of free(&array_of_struct[i].arr)
Thank you all for the help.
Don't do this:
structure.arr = new_arr;
That's not a copy of array content. That simply reassigns the pointer.
That means you are replacing the pointer with an allocation from somewhere else. At best, you'll have a memory leak from not freeing the original allocation. At worst, you'll crash because you attempt to free new_arr which is a stack array (invalid to invoke free on that address).
Do this instead, copy the array contents instead of overwriting the pointer:
memcpy(structure.arr, new_arr, arr_size * sizeof(int));
But if you just want to "zero out" the original allocation (as you implied), you just need to do this:
memset(structure.arr, '\0', arr_size * sizeof(int));
Or just use calloc instead of malloc to allocate and zero-out the contents at the same time.
structure->arr = calloc(arr_size, sizeof(int));
Update
But I still get the same arror when trying to free structure.arr. Also if I try to use mempcy. Could there be something wrong with free(&array_of_struct[i].arr)?
You need to pass to free exactly what was assigned from malloc.
So instead of this:
free(&array_of_struct[i].arr);
This:
free(array_of_struct[i].arr);
int *p = malloc(size);
int arr[size];
p = arr; // Not good. The memory we allocated above is now lost.
free(?); // We don't have a pointer to the allocated memory
int *p = malloc(size);
int arr[size];
int *q = arr;
p = arr; // Ok, because we have saved the pointer so we can free later
free(q);
int *p = malloc(size);
int arr[size];
memcpy(p, arr, size * sizeof *p);
free(p); // Works fine. We have not overwritten the pointer
You get this error since you can free only memory that was malloc'd.
when you write int new_arr[SIZE] you allocate the array on the stack, so you don't need to free it (you can say it will be "freed" when you leave the function in which you allocated it).
As for your struct, if you're aiming for an array that has a constant size that you know in advance, I would recommend that you implement it like this:
struct my_struct {
int arr[SIZE];
}
This will allocate the array as part of the struct (in my opinion this is more readable). So when you define an instance of this struct in your program it's sufficient to write:
struct my_struct s;
and the array will be allocated as well. In this case, you won't need to free it since you won't malloc it.
If you don't know the size of the array in advance, then it would be better to first allocate the memory using malloc and then use memcpy like #selbie suggested.
Strait to the point.
I have a struct with a string, char and int.
The struct is created dynamically because i will need it in different parts of my program.
struct A
{
char staticString[20];
char* dynamicString;
char character;
int integer;
};
I know if i want to create a struct i call:
A example = (A)malloc(sizeof(A));
In order to populate the dynamicString and int i used:
example->dynamicString = (char*)malloc(sizeof(char*));
example->integer = (int)malloc(sizeof(int));
Unfourtanetly when i tried to populate staticString and char it didn't worked.
Don't even ask what was my code for those, i tried a lot of combinations from everywhere.
In addition to that can somebody show me examples how to write/read those values?
Thanks in advance.
First things first:
You're using C, and by the way you've defined the structure, you need to declare the pointer like so:
struct A *example;
Next, malloc returns a pointer, so you need to cast to a pointer (and not to a structure):
(struct A *)malloc(sizeof(struct A));
Secondly, I'm not sure why but hey:
- you're trying to dynamically allocate an int in the structure. As I said previously, malloc returns a pointer, so in your structure you need an int pointer like so "int *integer;"
- you're trying to allocate a dynamic string, however you're not doing it properly, here is what I think you want
example->dynamicString = (char *)malloc(sizeof(char) * 10);
Where 10 is the size of your dynamic string.
Edit:
you may also populate the integer in your struct statically or dynamically, but I think you intended the static approach:
example->integer = 123;
The dynamic approach would be (assuming you have int *integer in your struct):
example->integer = (int *)malloc(sizeof(int));
*(example->integer) = 123;
Every time you create a new struct the memory in the heap is set to size of :
sizeof(char)*20 + sizeof(char pointer) +sizeof(char)+ sizeof(int).
If you want to save a string that will be pointed to by your char pointer- then you ask for allocation in heap for the size of that string- and malloc returns the pointer to that memory allocation on heap.
So, you already have a space for your char array, char pointer, char and int that was allocated when you asked to make a new struct and do not need to allocate it again.
also, keep in mind malloc returns a pointer to the allocated place on the heap- so if you malloc(sizeof(int)) you get a pointer to a memory allocation for an int on the heap- which is pointed to by a int pointer Not an int.
good luck!
I don't know what is the correct way to allocate memory dynamically:
I have a .csv file which has like 50 lines and I need to allocate enough space in memory to save each line of the file in one space of the struct vector.
Also, I know that the return of malloc is the first position of the allocated memory space.
Example:
typedef struct{
int a;
float b;
char name[10]; //This will be set dynamically too, later...
}my_struct;
int main(){
int *p_array;
size_t vector_size = 2; //Same as doing: my_struct struc[2] ?
p_array = (int *) malloc(vector_size * (int));
my_struct struc[p_array];
return 0;
}
Is it right? If not which is the right way of doing it. I got no errors, but I don't know why it doesn't seems right.
It's completely wrong, starting here
This is wrong
p_array = (int *) malloc(vector_size * (int));
/* ^ what is this? */
if you want an array of integers of vector_size size you need
p_array = malloc(vector_size * sizeof(int));
/* ^ the sizeof operator */
This doesn't make sense at all
my_struct struc[p_array];
maybe you mean?
my_struct struc[vector_size];
above you are passing a pointer where an integer should go, if this compiles then what is happening is that the address stored in the pointer is evaluated as an integer and hence your struc array has a size very different than what you think
If you use the corrected version of this, the malloc() makes absolutely no sense, so you don't really need it.
If you want to allocate the struc array dynamically then
my_struct *array;
array = malloc(elementCount * sizeof(my_struct)):
if (array == NULL)
pleaseDoNot_Use_array_AndProbably_AbortHere();
/* you can use it here, and when you finish */
free(array);
If you enable compiler warnings there will be a few warnings that will let you know some of the things I mentioned above.
Also, in c There is no need to cast malloc()
Hey guys (be forewarned that this question makes me feel n00b so I probably am),
I'm able to dynamically create an array and I'm able to use qsort effectively for a statically created array but am having trouble using qsort on a dynamically created one. I think I'm stumbling on my use of pointers.
struct my_struct {
FILE *fp;
int i;
};
So the array contains the above struct and I'd like to sort it by the int value.
Statically, I can do something like this:
struct my_struct array[4];
And sort:
qsort((void *) &array, sizeof(array) / sizeof(struct my_struct), sizeof(struct my_struct), *compare);
--
If I create the array thus:
struct my_struct* = malloc(sizeof(struct process) * 4);
Everything compiles and runs, however execution never goes into the compare function.
Any help would be greatly appreciated
sizeof(array) is (sizeof(struct my_struct) * array_size) for constant-size array, but it's only pointer size for dynamic one. You have to calculate actual size (one you passed to malloc) yourself and put it into qsort call.
Your invocation of qsort only works by accident:
qsort((void *) &array, sizeof(array) / sizeof(struct my_struct), sizeof(struct my_struct), *compare);
The address of an array has the same value but a different type from the address of the zeroth element of the array. The cast to void * is also superfluous; and the dereference of the comparator function is also aconventional. Normally, that'd be written:
qsort(array, sizeof(array) / sizeof(array[0]), sizeof(struct my_struct), compare);
Or:
qsort(array, sizeof(array) / sizeof(array[0]), sizeof(array[0]), compare);
If you have a dynamically allocated structure:
size_t num_items = 4;
struct my_struct *dynarr = malloc(sizeof(struct my_struct) * num_items);
or:
struct my_struct *dynarr = malloc(sizeof(*dynarr) * num_items);
then you will be specifying the number of elements differently in the call to qsort, but the rest is essentially unchanged:
qsort(dynarr, num_items, sizeof(*dynarr), compare);
Note in particular that there is no & in front of dynarr, which is a simple pointer variable, for all it has a possibly misleading name.
Why your code went wrong
A guess, but a plausible guess. If you wrote:
qsort(&dynarr, sizeof(dynarr) / sizeof(dynarr[0]), sizeof(dynarr[0]), compare);
then sizeof(dynarr) is the size of a pointer (say 8 bytes in a 64-bit program), and sizeof(dynarr[0]) is 16 bytes, so the size (number of elements) that you tell qsort() to sort is 0 (because 8 / 16 == 0), so the comparator would never be called. If your program is compiled as a 32-bit program, the sizes are 4 bytes for the pointer and 8 for the structure, so the result is still 0.
Note that if instead you passed 4 or num_items as the size of the array, then you'd get a crash. The address of dynarr is the wrong address to pass to the function; you want to pass the address value that is held in dynarr, not the address at which dynarr itself is stored.
NB: You should show the qsort() that doesn't work so we don't have to guess what you've written.
Assuming we have a simple struct like:
typedef struct
{
int d1;
int d2;
float f1;
}Type;
Which is the correct when allocate memory for a new instance of it:
This:
// sizeof *t == sizeof(Type) ( gcc prints 12 bytes)
Type *t = malloc(sizeof *t);
or:
// sizeof pointer always == 4 (in my case also on gcc)
Type *t = malloc(sizeof(t));
Which is the correct?
This is the correct way:
Type *t = malloc(sizeof *t);
Why this is correct?
Because you correctly allocate a size big enough to hold a structure. *t points to a type Type.
This is incorrect way:
Type *t = malloc(sizeof(t));
Why this is Incorrect?
sizeof(t) returns size of pointer and not the actual type(i.e: not the size of the structure).
What you need to allocate is size big enough to hold a structure not size equal to pointer to structure.
Note that, Size of an pointer pointing to Any type is same on an system.
Why is the first approach better?
With the first approach, when you change Type, the malloc automatically changes size to be the correct value, you do not have to do that explicitly unlike other ways.
Also, the important part of writing an malloc call is finding the correct size that needs to be passed. The best way to do this is not to look anywhere (because that is when we make the mistake) but only at the left hand side of this malloc statement. Since, it is t in this case therefore the correct size will be sizeof(*t).
How to standardize use of malloc?
With above mentioned correct approach there is one problem say, if we want to malloc say 30 elements. Then our malloc expression becomes:
t = (T *) malloc(30 * sizeof (*T));
This is not the preferred way to write a malloc expression, because one can make a mistake which entering the number 30 in the malloc parameter. What we would like- irrespective of the number of elements required the malloc parameter should always be the standard sizeof(*x) or something similar.
So here is an approach with an example:
Suppose we have a pointer p, pointing to a single dimensional array of size 20, whose each element is struct node. The declaration will be:
struct node (*p) [20];
Now if we wish to malloc 20 elements of stuct node, and wish that pointer p should hold the return address of malloc then we have
p = (data-type of p) malloc (size of 20 elements of struct node);
To find the data type of p, for casting we just make the variable name disappear or replace p with a blank. So we now have
p = (struct node (*)[20] ) malloc(size of 20 elements of struct node);
We can't go very wrong over here because the compiler will complain if we are wrong. Finally the size! We just do the standard way we have described, that is
p = (struct node (*)[20] ) malloc(sizeof (*p));
And we are done!
Type *t = malloc(sizeof *t);
This is the correct way to allocate the amount of memory needed for a new instance.
Type *t = malloc(sizeof (t));
This will only allocate enough storage for a pointer, not an instance.
sizeof(*t), because t is of type Type* so that *t points to something of type Type.
But I would suggest to use this instead, because it's more readable and less error prone:
Type *t = malloc(sizeof(Type));
this one:
Type *t = malloc(sizeof(*t));
you allocate memory for the struct, not for a pointer.
The first is correct. Second will not allocate enough memory, because t has the size of a pointer.
Better yet is
Type *t = malloc(sizeof(Type));
Preferably: Type * t = malloc(sizeof(Type));
Arguably, sizeof *t works as well and allows you to change the actual type of *t without requiring you to modify two separate locations, but using the type rather than an expression in the initial allocation feels more readable and expressive... that's subjective, though. If you you want to keep your options open to change the type, I'd personally prefer factoring that change into the typedef rather than the variable declaration/initialization.