Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've got some trouble about a C function.
This is the function:
int* CalcMeanPower(int Media[], int** MeanPowerArray, int righe, int colonne)
{
int i=0, k=0;
int ArrayPower[] = {0, 0, 0, 0};
for (i=0; i<righe; i++)
{
for (k=0; k<colonne; k++)
{
ArrayPower[k] = ArrayPower[k] + MeanPowerArray[i][k] ;
}
}
for (k=0; k<colonne; k++)
{
Media[k] = (ArrayPower[k]/righe);
}
return Media;
}
This is how I call the function from the main:
VettoreMedia = CalcMeanPower(VettoreMedia, RefMeanPower, num_mean, N);
,where the variables are defined as follows:
int* RefMeanPower[N];
int* VettoreMedia;
int N=4, num_mean=5;
When I try to run the program it returns me a segmentation fault while trying to do:
for (k=0; k<colonne; k++)
{
Media[k] = (ArrayPower[k]/righe);
}
Could you please explain me what I'm doing wrong? I've searched through the net but I can't find the answer. This function is only a little piece of my C program, but I'm sure it faults in this cycle!
Please Help..
u have not initialized VetorreMedia befor passing to the function. since this is not initialized,Media also is pointing to unknown location so segmentation fault. VetorreMedia should have some default value.
If you run this in a debugger you will see where your segfault is occurring and be able to solve it from there.
Google gdb cheatsheet to get started.
You need to reserve memory for your variables/arrays.
RefMeanPower is just a array of plain uninitialized pointers. And VettoreMedia is just a plain uninitialized pointer.
for(int i = 0; i < N; ++i)
RefMeanPower[i] = malloc(sizeof(int) * num_mean);
// don't forget to free after usage
for(int i = 0; i < N; ++i)
free(RefMeanPower[i]);
Where you get RefMeanPower[N][num_mean] so swap k and i as indices or N and num_mean on creation.
and for VettoreMedia you can do
VettoreMedia = malloc(sizeof(int) * N);
// don't forget to free after usage
free(VettoreMedia);
or
int VettoreMedia[N];
// frees automatically when leaving scope
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am declaring a 2d array in a headers file like this : int **arr;
Then I'm allocating memory and I initialize it with zeros.
However I'm getting segmentation fault.
Here is my code :
arr = (int **)malloc(d * sizeof(int *));
for (int u=0; u<d; u++)
arr[u] = (int *)malloc(q * sizeof(int));
for(int i=0; i<d+1; i++)
{
for(int j=0; j<q+1; j++)
{
arr[i][j]=0;
}
}
d+1 and q+1 both outside the boundary.
Use d and q
If you want to initialize with zero use calloc() which is simple to use and reduces redundant operations
arr = (int **)malloc(d * sizeof(int *));
for (int u=0; u<d; u++)
scoreBoard[u] = (int *)calloc(q , sizeof(int));
This code will create 2d int array and initialize with zero
You are getting a segmentation fault because you are overstepping the array's bounds.
for (int i = 0; i < d + 1; i++)
Should become:
for (int i = 0; i < d; i++)
And similarly for the other one. Don't forget array indices go from 0 to 1 less than the size (in elements) of the array.
Also:
Was the memory for scoreboard allocated? Currently, you create an array called arr rather than for the scoreboard you are initializing, so scoreboard[u] may also be out of bounds regardless of the value of u.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
So, this is working fine... that means, no compiler errors, it seems that there is no memory leak and it is doing what I wanted it to do. That said should it be working? When I go to books_init I send a local variable to collection, doesn't it mean that when I go back to main it shouldn't be working? (or undefined behavior?). Also, in case you say that I have to malloc it, do I have to free it after? (commented on cleanup)
/* pseudo struct Collection{
size_t size, capacity;
Volume *volumes;
} */
void collection_init(Collection *col, size_t capacity){
col->size = 0;
col->capacity = capacity;
col->volumes = malloc(sizeof(Volume) * capacity);
}
void collection_resize(Collection *col, size_t capacity){
Volume *v = realloc(col->volumes, capacity * sizeof(Volume));
if(!v) return;
col->capacity = capacity;
col->volumes = v;
}
void collection_add(Collection *col, Volume *volume){
if(col->size >= col->capacity)
collection_resize(col, col->capacity * 2);
col->volumes[col->size++] = *volume;
}
void collection_clean(Collection *col){
//for(vol : col->vol) free(vol);
//should I free every element or just volumes?
free(col->volumes);
}
void books_init(Collection *col){
for(int i = 0; i < 25; ++i){
Volume v = {.swag = i};
collection_add(col, &v);
}
}
int main(){
Collection col;
collection_init(&col, 10);
books_init(&col);
for(int i = 0; i < col.size; ++i){
printf("\tVol[%d].id = %d\n", i, col.volumes[i].swag);
}
collection_clean(&col);
return 0;
}
Thanks for your time
This line in books_init
Volume v = {.swag = i};
creates a local variable called v with member swag initialized to i. The address of that variable is then passed to collection_add. That is allowed because v is still in scope.
This line in collection_add
col->volumes[col->size++] = *volume;
makes a copy of the contents of the Volume structure, and stores that copy in the memory that was allocated in collection_init.
After collection_add returns, the variable v in books_init goes out of scope, but that's OK because the contents of v were copied and saved in the memory that col->volumes points to.
When the program ends, collection_clean only needs
free(col->volumes);
to remove all of the Volume copies from memory.
The only flaw I see in your program occurs if realloc fails. In that case, you still write to the Volume array. This will cause a buffer overrun and memory corruption. To avoid this, the collection_add function should verify that the collection_resize function succeeded before performing the copy. For example, you could check again that col->capacity > col->size before doing the copy.
TL;DR your code is fine as long as the realloc always succeeds.
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 7 years ago.
Improve this question
here is my problem, I malloc my array like that:
e->map = malloc(sizeof(int *) * e->map_y);
i = -1;
while (++i < e->map_x)
e->map[i] = malloc(sizeof(int) * e->map_x);
where e->map_y = 14 and e->map_x = 10
The problem is I can't access (I have a segfault) elements after e->map[10][0] (included)
I tough about I invert x and y but it doesn't seem to be the case here.
I can post my entire code if necessary, thx
hi, I added the entire project on github for more details: https://github.com/42-hbock/fdf
this part of the code is in src/default_reading.c, the malloc is in the function char *default_reading(char *file, t_env *e) and I have the segmentation fault while accessing in void create_int_map(char *cmap, t_env *e)
Should be:
e->map = malloc(sizeof(int *) * e->map_y);
i = -1;
while (++i < e->map_y)
e->map[i] = malloc(sizeof(int) * e->map_x);
The change is having the while look at e->map_y instead of e->map_x. The rest of the code is the same.
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 8 years ago.
Improve this question
With my current implementation of code, I'm getting a segmentation fault that I think is caused by trying to store several char* in another char*. However, I don't know a way around this being fairly new to C. I'm in a GLUE Unix environment. The code compiles but does not fully execute.
Here's my method that I think is causing the issue.
int totalLogins = 0, selectedLogins = 0,dateIn[3], timeIn[3], dateOut[3], timeOut[3];
int latest = 0,earliest=30,loggedIn = 0, firstTime[7][3],firstDate[7][3],i;
char* user[12], firstUser[7][12];
bool first = true;
void checkAndSetEarliest(int day)
{
first = true;
for(i = 0; i < 3 && first; i++)
{
first = (timeIn[i]<firstTime[day][i]);
}
if(first)
{
for(i = 0; i < 3; i++)
{
firstTime[day][i] = timeIn[i];
firstDate[day][i] = dateIn[i];
}
printf("user = %s\n",user);
firstUser[day] = user;
}
}
timeIn[],firstTime[][],firstDate[][], and dateIn[] are all ints
firstUser[] and user[] are char*
I'm trying to edit the contents of firstUser with the value of user.
First, the way you are using user[] in printf, it is suppose to be a char array, not an array of pointer to char (what you have declared).
Secondly, firstuser is a 2d arrray and you are using it as a 1d array.
You really need to show the definition of the variables this function uses. Fair chance that last line should be changed to:
strcpy( FirstUser[day], user );
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
well, i'm working in C. I want to make a function that return a matrix[][].
This is my function:
char **mapa(int largo,int ancho)
{
char **matriz;
int i,j;
matriz = (char **)malloc(sizeof(char)*largo);
for(i = 0; i < largo; ++i)
{
matriz[i]= (char *)malloc(sizeof(char)*ancho);
}
for(i = 0; i < largo; i++)
{
for(j = 0; j < ancho; j++)
{
matriz[i][j] = 'k';
}
}
for(i = 0; i < largo; i++)
{
for (j = 0; j < ancho; j++)
{
printf("%c",matriz[i][j]);
}
}
return matriz;
}
Using gdb it give me this:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004008b8 in mapa (largo=10, ancho=10) at main.c:18
18 matriz[i][j] = 'k';
I don't know where the error is, if someone can give me a hand i'll be very gratefull.
Many thanks.
char **matriz;
int i,j;
matriz = (char **)malloc(sizeof(char)*largo);
Your matriz variable is a pointer to an array of pointers, each of which points to an array of char. You first need to allocate memory for the array of pointers, which requires largo times the size of the pointers, which is sizeof (char *). You only allocate space for largo times the size of a single char.
The easiest way to get the allocation right is to use the following pattern:
p = malloc (n * sizeof *p);
In other words, allocate n times the size of whatever p points to. This will automatically allocate the right amount regardless of the type of p, assuming you get the n right. If you're declaring the pointer in the same line, it looks a little different:
T *p = malloc (n * sizeof *p); /* For some type T */
In this case there is an asterisk before p on both sides. This difference is something you will have to be aware of, especially when you have more than one level of indirection.
Your first allocation, using this pattern, would look like this:
matriz = malloc (largo * sizeof *matriz);
and the second:
matriz[i] = malloc (ancho * sizeof *matriz[i]);
Note, that you never have to cast a void pointer (the return value of malloc()), and that the argument to the sizeof operator only needs parenthesis when it's a type name. When you get rid of the parenthesis, and place the quantity (ancho) before the sizeof operator, the result is an expression that is very clean and easy to understand. That is, of course, my personal opinion.
Your first malloc casts to a pointer of pointer's but that doesn't mean it is. If you look at your 2nd malloc you're allocating the same thing. So when you dereference matriz[i][z] you're dereferencing a charater, not a pointer. So I believe, it's been a while since I've done C, your first malloc needs to be (char**)malloc(sizeof(char*)*largo).