Segmentation Fault with pointers arrays - c

I have a Segmentation fault according to my debugger but I don't know why.
Here is the code involved. Did I miss something ?
typedef struct Process Process;
struct Process {
unsigned int m_id;
unsigned int m_size;
int m_startAddr;
};
unsigned int** memory = calloc(MEMORY_SIZE, sizeof(unsigned int*));
Process** processList = calloc(MEMORY_SIZE, sizeof(Process*));
unsigned int itr;
unsigned int nb_process = 0;
int previous_process = -1;
for(itr = 0; itr < MEMORY_SIZE; ++itr)
{
if(memory[itr] != NULL)
{
previous_process = *memory[itr]; // works but risk of integer overflow
processList[nb_process]->m_id = *memory[itr]; // segfault
processList[nb_process]->m_size = 1;
processList[nb_process]->m_startAddr = itr;
nb_process++;
}
}
}
EDIT : I tried to make the following changes :
Process* processList = calloc(MEMORY_SIZE,sizeof(Process));
unsigned int** memory = calloc(MEMORY_SIZE, sizeof(unsigned int*));
unsigned int nb_process = 0;
int previous_process = -1;
unsigned int itr;
Process temp;
for(itr = 0; itr < MEMORY_SIZE; ++itr)
{
/* if memory unit is not occupied */
if(memory[itr] != NULL)
{
/* if process is not known yet */
if(*memory[itr] != previous_process)
{
previous_process = *memory[itr];
printf("previous_process %u \n", previous_process);
temp.m_id = *memory[itr];
temp.m_size = 1;
temp.m_startAddr = itr;
processList[nb_process] = temp;
nb_process++;
}
/* if the process is already known */
else
{
printf("size %u \n", processList[nb_process].m_size);
processList[nb_process].m_size++;
}
}
}
The output of previous_process is correct. However, the output of size got a problem. First, it has always two values below what it should (14 instead of 16, 30 instead of 32; etc...) at the end of the for loop. Worse, the count start at 0, while it should start at 1, since i initialize temp.m_size with one before copying it into processList. So the copy doesn't work... Why ? Should i use memcpy ?

You do this:
unsigned int** memory = calloc(MEMORY_SIZE, sizeof(unsigned int*));
*memory[0]
You allocated space for an array of pointers, but then you dereference those pointers. But they are all zero (which on most systems is NULL, but in any case is not a valid pointer because it came from nowhere). That can't work.

In addition to John's answer above you are also allocating an array of pointers
Process** processList = calloc(MEMORY_SIZE, sizeof(Process*));
unsigned int nb_process = 0;
You must ensure that each of that array of pointers is initialized with something valid before de-referencing them as they are.

Related

How do you return a pointer from a function outside of main()

My question is aboutt dynamic memory allocation in C. I have been asked to dynamically allocate an array of n longs, and return the pointer to the first element of this array. I have some code to test the output of this but the memory allocation is failing.
long* make_long_array(long n)
{
int i;
int *a;
a = (int*)malloc(sizeof(int)*n);
if (a == NULL) {
printf("ERROR: Out of memory\n");
return 1;
}
for (i = 0; i < n; *(a + i++) = 0);
return *a;
}
Im getting an error on two lines saying
'error: return makes pointer from integer without cast'
this occurs for the lines
return 1;
and
return *a;
I'm not entirely sure how to fix this. I think the error in return 1; being that I am trying to return an integer when it is looking for a pointer? But I am not sure how to fix it for the return of the pointer. Any help would be much appreciated.
To fix your original version:
long* make_long_array(/* long not the correct type for sizes of objects */ size_t n)
{
// int i; define variables where they're used.
/* int you want to return a */ long *a; // array.
a = /* (int*) no need to cast */ malloc(sizeof(/* int */ you want */ long /*s, remember? *) */ ) * n);
if (a == NULL) {
printf("ERROR: Out of memory\n"); // puts()/fputs() would be sufficient.
return /* 1 */ NULL; // 1 is an integer. Also it is uncommon to return
} // anything other than NULL when a memory allocation
// fails.
for (size_t i = 0; i < n; /* *(a + i++) = 0 that falls into the category obfuscation */ ++i )
/* more readable: */ a[i] = 0;
// return *a; you don't want to return the first long in the memory allocated
return a; // but the address you got from malloc()
}
A Better Waytm to write such allocations is
FOO_TYPE *foo = malloc(NUM_ELEMENTS * sizeof(*foo)); // or
BAR_TYPE *bar = calloc(NUM_ELEMENTS, sizeof(*bar));
By using *foo and *bar as the operand of sizeof you don't have to worry about changing it when the type of foo or bar changes.
Your function can be simplified to
#include <stddef.h> // size_t
#include <stdlib.h> // calloc()
long* make_long_array(size_t size) // size_t is guaranteed to be big enough to hold
{ // all sizes of objects in memory and indexes
return calloc(size, sizeof(long)); // into them. calloc() initializes the memory
} // it allocates with zero.
// if you really want an error-message printed:
long* make_long_array(size_t size)
{
long *data = calloc(size, sizeof(long));
if (!data) // calloc() returned NULL
fputs("Out of memory :(\n\n", stderr); // Error messages should go to stderr
return data; // since it is unbuffered*) and
} // might be redirected by the user.
*) so the user gets the message instantly.
Also there is no need to cast the result of *alloc() since they return a void* which is implicitly convertible in every other pointer type.
Could be written as a macro so it not only works for long but for any type:
#include <stddef.h>
#include <stdlib.h>
#define MAKE_ARRAY(TYPE, COUNT) calloc((COUNT), sizeof((TYPE)))
// sample usage:
int main(void)
{
int *foo = MAKE_ARRAY(*foo, 12);
long *bar = MAKE_ARRAY(*bar, 24);
char *qux = MAKE_ARRAY(*qux, 8);
free(qux);
free(bar);
free(foo);
}

Garbage value even after initializing members of dynamically allocated struct array

I have a dynamically allocated array of structures, 'buff'. Each element is a structure that has a few integer variables and a pointer 'buffer_ptr' which points to another dynamically allocated array of structures. The size of both arrays is given as command line input.
int buffer_size;
int user_num;
struct tuple
{
char userID[5];
char topic[16];
int weight;
};
struct buff_ctrl
{
struct tuple* buffer_ptr;
int in;
int out;
int numItems;
int done;
};
The arrays are created and initialized in main() as follows:
int main(int argc, char* argv[])
{
void *status;
pthread_t mapThd;
if(argc != 4)
{
printf("Input format: ./combiner <buffer_size> <number_of_users> <input_file>\n");
return -1;
}
buffer_size = atoi(argv[1]);
user_num = atoi(argv[2]);
struct buff_ctrl *buff = (struct buff_ctrl*)malloc(user_num * sizeof(struct buff_ctrl));
for(int i=0; i<user_num; i++)
{
struct buff_ctrl* curr_buff = (buff + (i*sizeof(struct buff_ctrl)));
struct tuple *ptr = (struct tuple*)malloc(buffer_size * sizeof(struct tuple));
curr_buff->buffer_ptr = ptr;//points to another array
curr_buff->in = 8;
curr_buff->out = 4;
curr_buff->numItems = 7;
curr_buff->done = 0;
printf("%p\n",curr_buff);
}
Then, I need to pass the 'buff' pointer as an argument when creating thread using pthread_create:
pthread_create(&mapThd, NULL, mapper, (void*)buff);
pthread_join(mapThd, &status);
free(buff);
/*end of main*/
My function pointer is as follows:
void* mapper(void *buff)
{
struct buff_ctrl* arr = (struct buff_ctrl *)buff;
struct buff_ctrl* temp_ptr;
printf("######################################################\n");
for(int k=0; k<user_num; k++)
{
/*Printing just to check values */
temp_ptr = arr + (k*sizeof(struct buff_ctrl));
printf("buffer ptr = %p\n", temp_ptr->buffer_ptr);
printf("in = %d\n", temp_ptr->in);
printf("out = %d\n", temp_ptr->out);
printf("numItems = %d\n", temp_ptr->numItems);
}
printf("######################################################\n");
pthread_exit((void*)buff);
}
But, when I print the values of 'buffer_ptr' from the created thread (only one), for ODD number of user_num, there is always ONE element of the array 'buff' which gives garbage value after pthread_create statement! When the values are checked in main itself after removing calls to pthread, it runs fine.
This line
struct buff_ctrl* curr_buff = (buff + (i*sizeof(struct buff_ctrl)));
should be
struct buff_ctrl* curr_buff = buff + i;
buff + i is pointer arithmetic and the compiler already takes the size of the
object pointed to by buff into consideration. By doing i*sizeof(struct buff_ctrl) you are assigning
a pointer that may be after the allocated memory.
As general suggestion:
Don't cast malloc. And instead of using sizeof(<type>), use sizeof *variable, this is more safe, because
it's easier to make mistakes when writing sizeof(<type>).
So:
struct buff_ctrl *buff = malloc(user_num * sizeof *buff);
...
struct tuple *ptr = malloc(buffer_size * sizeof *ptr);
And you don't need to declare a separate pointer, you can do:
for(int i=0; i<user_num; i++)
{
buff[i].buffer_ptr = malloc(buffer_size * sizeof *buff[i].buffer_ptr);
buff[i].in = 8;
buff[i].out = 4;
buff[i].numItems = 7;
buff[i].done = 0;
}
Also you should always check for the return value of malloc. If it returns
NULL, you cannot access that memory.
This is wrong:
struct buff_ctrl* curr_buff = (buff + (i*sizeof(struct buff_ctrl)));
When you do pointer arithmetic, it operates in units of the size of what the pointer points to, so you don't need to multiply by sizeof. As a result, you're effectively multiplying twice and accessing outside the array bounds.
Just treat buff as an array, rather than dealing with pointers.
for(int i=0; i<user_num; i++)
{
struct tuple *ptr = malloc(buffer_size * sizeof(struct tuple));
buff[i].buffer_ptr = ptr;//points to another array
buff[i].in = 8;
buff[i].out = 4;
buff[i].numItems = 7;
buff[i].done = 0;
}
Also, see Do I cast the result of malloc?
You have a fundamental error.
Pointer arithmetics works by adding the offset in multiples of the pointer type, so adding the offset yourself will not work as you apparently expect it to.
If it was a char * pointer then you would need to add the offset manually, increments would be multiplied by one. But in your case increments by n are multiplied by the size of the pointer base type.
There are times when doing pointer arithmetics with the addition notation makes sense, but most of the time it's much clearer to write index notation instead.

Pointer is changing after function call, C

So I've written this program to represent a car park as a bitset, each space in the car park being one bit. I have a checkSpace function to check if a space is occupied or not and for some reason the pointer to my car park bitset changes or the data changes after I pass it into the function. To test it I set up the car park, I checked a space, then checked it again immediately after and for some reason the return value is changing when it shouldn't be. Any help would be appreciated!
struct carPark{
int spaces, levels;
unsigned char * park;
};
struct carPark * emptyCarPark(int levels, int spaces){
int chars = (spaces*levels)/8;
if((spaces*levels)%8 != 0){
chars++;
}
unsigned char park[chars];
for (int i = 0; i < chars; ++i){
park[i] = 0;
}
unsigned char * ptr = &park[0];
struct carPark * myPark = malloc(sizeof(struct carPark));
myPark->park = ptr;
myPark->spaces = spaces;
myPark->levels = levels;
return myPark;
}
int checkSpace(int level, int spaceNum, struct carPark * carpark){
int charPosition = ((level*carpark->spaces) + spaceNum)/8;
int bitPosition = ((level*carpark->spaces) + spaceNum)%8;
if(carpark->park[charPosition]&&(1<<bitPosition) != 0){
return 1;
}
return 0;
}
int main(int argc, char const *argv[]){
struct carPark * myPark = emptyCarPark(5,20);
printf("1st check: %d\n",checkSpace(1,1,myPark));
printf("Second check: %d\n",checkSpace(1,1,myPark));
return 0;
}
So when I run the program I get:
1st check: 0
Second check: 1
Look at the code below - in emptyCarPark() you are allocating the park array on the stack, and then returning a pointer to it. As soon as the function returns, the park array is no longer allocated and you have a dangling pointer - for more information, see: Cause of dangling pointers (Wikipedia)
unsigned char park[chars];
for (int i = 0; i < chars; ++i){
park[i] = 0;
}
// This is the pointer to an object on the stack.
unsigned char * ptr = &park[0];
struct carPark * myPark = malloc(sizeof(struct carPark));
myPark->park = ptr;

Heap block at X modified at Y past requested size - freeing allocated memory

Program crashing when freeing allocated memory: "Heap block at X modified at Y past requested size of 21".
Running function getUstr, crashes on free(uStr).
Can someone please help me find where am I using unallocated memory?
Thank you!
int HexToUChars(char* hexStr, unsigned char **str){
int i, n;
int strLen = strlen(hexStr)/2;
for (i = 0; i < (int)strLen; i++) {
sscanf_s(hexStr + 2 * i*sizeof(unsigned char), "%02X", *str+i*sizeof(unsigned char));
}
return 0;
}
int getUStr(){
char *hexStr = "E7CA7905DD060F0E437C885BF13DED9243B1D2BD94CB11223DA71360A8F7D2D4";
unsigned char *uStr;
size_t strLen = (size_t)strlen(hexStr) / 2;
uStr = calloc((strLen + 1), sizeof(unsigned char));
if (uStr != NULL){
HexToUChars(hexStr, &uStr);
free(uStr);//Error : Heap block at X modified at Y past requested size of 21
}
}
For sscanf() and friends, %02X expects a pointer to an unsigned int, but you're giving it a pointer to an unsigned char. If an unsigned int is, say, 4 bytes on your system, then you're going to write past the end of your allocated memory on the last couple of iterations through that loop.
You should provide a pointer to a (local) unsigned int to sscanf_s(), and then assign the value of that to your unsigned char.
there were several errors in the presented code.
those errors are fixed here
I did add a few $includes, etc so the file would compile
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int HexToUChars( const char *, unsigned char * );
int getUStr( void );
int HexToUChars(const char* pHexStr, unsigned char *pStr)
{
int i = 0; // loop index
//int n; // this raises a compiler warning about unused variable
// the strLen is using a reserved word, with only a capitalization change,
// I.E. very poor program practice
int hexStrLen = (int)strlen(pHexStr) >> 1; // this assumes that hexStr is an even number of bytes
for (i = 0; i < hexStrLen; i++)
{
pStr[i] = pHexStr[2*i] - '0';
pStr[i] += pHexStr[(2*i)+1] - '0';
} // end for
return 1;
} // end function: HexToUChars
int getUStr()
{
const char* pHexStr = "E7CA7905DD060F0E437C885BF13DED9243B1D2BD94CB11223DA71360A8F7D2D4";
unsigned char *pStr;
int hexStrLen = strlen(pHexStr) / 2;
if( NULL == (pStr = calloc( (hexStrLen + 1), sizeof(unsigned char) ) ) )
{
perror( "calloc failed" );
exit( EXIT_FAILURE );
}
// implied else, calloc successful
HexToUChars(pHexStr, pStr);
if( strlen((const char*)pStr) != hexStrLen )
{
perror( "problem in HexToUChars");
}
printf( "%s", pStr );
free(pStr);
return(0); // without this, compiler raises warning about no return statement
}

C Programming: malloc() for a 2D array (using pointer-to-pointer)

yesterday I had posted a question: How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?
From the answers I got, I was able to understand what mistake I was doing.
I'm facing a new problem now, can anyone help out with this?
I want to dynamically allocate a 2D array, so I'm passing a Pointer-to-Pointer from my main() to another function called alloc_2D_pixels(...), where I use malloc(...) and for(...) loop to allocate memory for the 2D array.
Well, after returning from the alloc_2D_pixels(...) function, the pointer-to-pointer still remains NULL, so naturally, when I try accessing or try to free(...) the Pointer-to-Pointer, the program hangs.
Can anyone suggest me what mistakes I'm doing here?
Help!!!
Vikram
SOURCE:
main()
{
unsigned char **ptr;
unsigned int rows, cols;
if(alloc_2D_pixels(&ptr, rows, cols)==ERROR) // Satisfies this condition
printf("Memory for the 2D array not allocated"); // NO ERROR is returned
if(ptr == NULL) // ptr is NULL so no memory was allocated
printf("Yes its NULL!");
// Because ptr is NULL, with any of these 3 statements below the program HANGS
ptr[0][0] = 10;
printf("Element: %d",ptr[0][0]);
free_2D_alloc(&ptr);
}
signed char alloc_2D_pixels(unsigned char ***memory, unsigned int rows, unsigned int cols)
{
signed char status = NO_ERROR;
memory = malloc(rows * sizeof(unsigned char** ));
if(memory == NULL)
{
status = ERROR;
printf("ERROR: Memory allocation failed!");
}
else
{
int i;
for(i = 0; i< cols; i++)
{
memory[i] = malloc(cols * sizeof(unsigned char));
if(memory[i]==NULL)
{
status = ERROR;
printf("ERROR: Memory allocation failed!");
}
}
}
// Inserted the statements below for debug purpose only
memory[0][0] = (unsigned char)10; // I'm able to access the array from
printf("\nElement %d",memory[0][0]); // here with no problems
return status;
}
void free_2D_pixels(unsigned char ***ptr, unsigned int rows)
{
int i;
for(i = 0; i < rows; i++)
{
free(ptr[i]);
}
free(ptr);
}
One mistake is posting code that won't compile :). Below is corrected code with my comments in
/* this style */:
/* Next four lines get your code to compile */
#include <stdio.h>
#include <stdlib.h>
#define NO_ERROR 0
#define ERROR 1
/* prototypes for functions used by main but declared after main
(or move main to the end of the file */
signed char alloc_2D_pixels(unsigned char*** memory, unsigned int rows, unsigned int cols);
void free_2D_pixels(unsigned char** ptr, unsigned int rows);
/* main should return int */
int main()
{
unsigned char** ptr;
/* need to define rows and cols with an actual value */
unsigned int rows = 5, cols = 5;
if(alloc_2D_pixels(&ptr, rows, cols) == ERROR) // Satisfies this condition
printf("Memory for the 2D array not allocated"); // ERROR is returned
if(ptr == NULL) // ptr is NULL so no memory was allocated
printf("Yes its NULL!");
else
{
/* Added else clause so below code only runs if allocation worked. */
/* Added code to write to every element as a test. */
unsigned int row,col;
for(row = 0; row < rows; row++)
for(col = 0; col < cols; col++)
ptr[0][0] = (unsigned char)(row + col);
/* no need for &ptr here, not returning anything so no need to pass
by reference */
free_2D_pixels(ptr, rows);
}
return 0;
}
signed char alloc_2D_pixels(unsigned char*** memory, unsigned int rows, unsigned int cols)
{
signed char status = NO_ERROR;
/* In case we fail the returned memory ptr will be initialized */
*memory = NULL;
/* defining a temp ptr, otherwise would have to use (*memory) everywhere
ptr is used (yuck) */
unsigned char** ptr;
/* Each row should only contain an unsigned char*, not an unsigned
char**, because each row will be an array of unsigned char */
ptr = malloc(rows * sizeof(unsigned char*));
if(ptr == NULL)
{
status = ERROR;
printf("ERROR: Memory allocation failed!");
}
else
{
/* rows/cols are unsigned, so this should be too */
unsigned int i;
/* had an error here. alloced rows above so iterate through rows
not cols here */
for(i = 0; i < rows; i++)
{
ptr[i] = malloc(cols * sizeof(unsigned char));
if(ptr[i] == NULL)
{
status = ERROR;
printf("ERROR: Memory allocation failed!");
/* still a problem here, if exiting with error,
should free any column mallocs that were
successful. */
}
}
}
/* it worked so return ptr */
*memory = ptr;
return status;
}
/* no need for *** here. Not modifying and returning ptr */
/* it also was a bug...would've needed (*ptr) everywhere below */
void free_2D_pixels(unsigned char** ptr, unsigned int rows)
{
/* should be unsigned like rows */
unsigned int i;
for(i = 0; i < rows; i++)
{
free(ptr[i]);
}
free(ptr);
}
In your alloc_2D_pixels function, you need another level of indirection when accessing memory. As it is now, you only modify the parameter, not the pointer pointed to by the parameter. For example,
memory = malloc(rows * sizeof(unsigned char** ));
// becomes
*memory = malloc(rows * sizeof(unsigned char** ));
// and later...
memory[i] = malloc(cols * sizeof(unsigned char));
// becomes
(*memory)[i] = malloc(cols * sizeof(unsigned char));
(basically, anywhere you are using memory, you need to use (*memory); the parentheses are only needed when you are using subscripts to ensure that the operators are applied in the correct order)
It also looks like, You are using uninitialized rows and cols variables
Using multidimensional arrays in this way in C is "suboptimal" for performance.
In no unclear words: Please do not use - and definitely not initialize - multidimensional arrays in the way you've illustrated. Multiple calls to malloc() will create you a batch of disjoint memory locations that doesn't map well to how actual graphics (as contiguous, single buffers) are stored anywhere. Also, if you have to do it hundreds or thousands of times, malloc() can be hideously expensive.
Also, due to the fact that you're using malloc() very often, it's also a nightmare (and bug to bite you eventually) for cleaning up. You've even mentioned that in the comments in your code, and yet ... why ?
If you absolutely must have this ptr[rows][cols] thing, create it better like this:
signed char alloc_2D_pixels(unsigned char*** memory,
unsigned int rows,
unsigned int cols)
{
int colspan = cols * sizeof(char);
int rowspan = rows * sizeof(char*);
unsigned char **rowptrs = *memory = malloc(rowspan + rows * colspan));
/* malloc failure handling left to the reader */
unsigned char *payload = ((unsigned char *)rowptrs) + rowspan;
int i;
for (i = 0; i < rows; payload += colspan, i++)
rowptrs[i] = payload;
}
that way you're allocating only a single block of memory and the whole thing can be freed in one go - ditch free_2D_pixels().

Resources