Abort trap: 6, using memcpy to copy an array - c

I'm trying to learn how to copy a space in memory that was allocated with malloc. I'm assuming the best way to go about this would be to use memcpy.
I am more familiar with Python. The equivalent of what I'm trying to do in Python would be:
import copy
foo = [0, 1, 2]
bar = copy.copy(foo)
Here is was I have so far.
/* Copy a memory space
* */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
// initialize a pointer to an array of spaces in mem
int *foo = malloc(3 * sizeof(int));
int i;
// give each space a value from 0 - 2
for(i = 0; i < 3; i++)
foo[i] = i;
for(i = 0; i < 3; i++)
printf("foo[%d]: %d\n", i, foo[i]);
// here I'm trying to copy the array of elements into
// another space in mem
// ie copy foo into bar
int *bar;
memcpy(&bar, foo, 3 * sizeof(int));
for(i = 0; i < 3; i++)
printf("bar[%d]: %d\n", i, bar[i]);
return 0;
}
The output of this script is as follows:
foo[0]: 0
foo[1]: 1
foo[2]: 2
Abort trap: 6
I'm compiling the script with gcc -o foo foo.c. I'm on a 2015 Macbook Pro.
My questions are:
Is this the best way to copy an array that was created with malloc?
What does Abort trap: 6 mean?
Am I just misunderstand what memcpy does or how to use it?
Kind regards,
Marcus Shepherd

The variable bar has no memory allocated to it, it is just an uninitialised pointer.
You should do that as you did with foo earlier
int *bar = malloc(3 * sizeof(int));
And then you need to drop the & address-of operator as
memcpy(bar, foo, 3 * sizeof(int));

Related

Segmentation fault when using sprintf in dynamically allocated array

I am converting integers to strings and adding them to a dynamically allocated array. The problem is that it is causing a segfault. I don't understand why it is happening.
#include <stdio.h>
#include <stdlib.h>
int main() {
char *x = malloc(10 * sizeof(char));
x[0] = malloc(10 * sizeof(char));
sprintf(x[0],"%d",10);
for(int i = 0; i < 10;i++){
free(x[i]);
}
free(x);
return 0;
}
To allocate an array whose elements are char*, the pointer to point the array should be char**, not char*.
Also you mustn't use values in buffer allocated via malloc() and not initiaized. The values are indeterminate and using them invokes undefined behavior.
#include <stdio.h>
#include <stdlib.h>
int main() {
/* correct type here (both variable and allocation size) */
char **x = malloc(10 * sizeof(char*));
x[0] = malloc(10 * sizeof(char));
sprintf(x[0],"%d",10);
/* initialize the other elements to pass to free() */
for (int i = 1; i < 10; i++) x[i] = NULL;
for(int i = 0; i < 10;i++){
free(x[i]);
}
free(x);
return 0;
}
If you want a dynamic allocated array of strings, you should declare your variable x as a pointer to an array of e.g. 32 chars. The you can allocate/deallocate an array of these using a single malloc and likewise a single free.
Like:
#define NUM_STRINGS 10
#define STRING_SIZE 32
int main() {
// declare x as a pointer to an array of STRING_SIZE chars
char (*x)[STRING_SIZE];
// Allocate space for NUM_STRINGS of the above array, i.e.
// allocate an array with NUM_STRINGS arrays of STRING_SIZE chars
x = malloc(NUM_STRINGS * sizeof *x);
if (x)
{
for (int i = 0; i < NUM_STRINGS; ++i)
{
sprintf(x[i], "%d", 10 + i);
}
for (int i = 0; i < NUM_STRINGS; ++i)
{
puts(x[i]);
}
free(x);
}
return 0;
}
Output:
10
11
12
13
14
15
16
17
18
19
The best way to determine the amount of memory to be used with malloc is this:
#include <stdio.h>
#include <stdlib.h>
#define N_STRINGS 10
#define STRING_SZ 10
int main() {
// if you use *x (the deferred subexpression) the compiler can calculate its
// sizeof easily, and no need to use a constant or something that has to be
// revised if you change the type of x. Also, calloc will give instead N_STRINGS
// pointers already initialized to NULL.
char **x = calloc(N_STRINGS, sizeof *x);
// to be able to free(x[i]) for all i, you need to initialize all pointers,
// and not only the first one.
int i; // I prefer this, instead of for(int i..., which is more portable with legacy code.
for (i = 0; i < N_STRINGS; i++) {
// char is warranted to be sizeof 1, you don't need to specify but the
// number of chars you want for each character array.
x[i] = malloc(STRING_SZ); // remember only STRING_SZ chars you have, so...
// better to use snprintf(), instead.
snprintf(x[i], // the buffer pointer
STRING_SZ, // the buffer size (STRING_SZ chars, incl. the final null char)
"%d", // the format string
10); // initialize all strings to the string "10" ???
}
// upto here we have made N_STRINGS + 1 calls to malloc...
// you should do something here to check that the allocations went fine, like
// printing the values or do some work on the strings, but that's up to you.
// now, everything should be fine for free() to work.
for(int i = 0; i < N_STRINGS; i++){
free(x[i]);
}
free(x); // ... and this is the N_STRINGS + 1 call to free.
return 0;
}
Check always that the number of free calls executed by your program has to be the same of the malloc calls you have made (before). A free call must free the memory allocated by one (and only one) call to malloc. You cannot free something that has not been acquired by malloc() (or calloc()) directly or indirectly. The same as it is bad use (but not necessary an error) to do a malloc that is not freed before the program ends (this is not true in non-hosted environments, e.g. embedded programs, in which the operating system doesn't deallocate the memory used by a program when it finishes, although)
By the way, the reason of your segmentation fault is precisely that you have made only two calls to malloc(), but you made 11 calls to free(). free() tries to free memory that malloc() has not allocated, or even worse, you don't own. Anyway, this drives you to Undefined Behaviour, which is something you don't desire in a program. In this case, you got a program crash.

realloc a 2d-array with a void function in c

I am trying to modify a 2D array from a void function.
#include <stdio.h>
#include <stdlib.h>
void try_by_reference(int **arr){
*arr = realloc(*arr, sizeof *arr * 2);
}
int main(int argc, char **argv){
// declare dynamic 2d-array and allocate memory
int (*arr)[2] = malloc(sizeof *arr * 10);
// fill array
for (int i=0; i<10; i++){
arr[i][0] = i;
arr[i][1] = i+10;
}
// declare and fill a simpler dynamic array
int *tarr = malloc(sizeof(int) * 10);
for (int i=0; i<10; i++)
tarr[i] = i*2;
try_by_reference(&tarr);
try_by_reference(&arr); <-- this gets warning
free(arr);
free(tarr);
return 0;
}
Compiler says:
warning: incompatible pointer types passing 'int (**)[2]' to parameter of type 'int **'
What am I doing wrong?
Thank you!
_"I am trying to modify a 2D array from a void function."_
Here are some tips, and fixes that will allow you to update memory to an array of two pointers to int. (see comment in-line with your code)
void try_by_reference(int **arr){
//always use a temporary variable to call realloc, otherwise if failed attempt - memory leak will occur
int *tmp = realloc(*arr, 2 * sizeof(*arr));//this effectively reduces memory from original 10, to 2 instances of int
if(!tmp)//always check return of realloc, if it fails free original memory and return
{
free(*arr);
//set pointer to NULL here to provide way to test before
//freeing later in process. (See 'Reference' below)
*arr = NULL;//to prevent problems in subsequent free calls
return;
}
else *arr = tmp;
}
int main(int argc, char **argv){
// declare dynamic 2d-array and allocate memory
int *arr[2] = {NULL, NULL};//this is an array of 2 pointers to int - each
//need to be allocated
//it will result in an array shaped as array[2][10]
//after following calls to malloc.
arr[0] = malloc(10*sizeof(arr[0]));//original provides memory for 10 instances of int
if(arr[0])
{
arr[1] = malloc(10*sizeof(arr[1]));
if(arr[1])
{
// fill array
//for (int i=0; i<10; i++){
for (int i=0; i<10; i++){
//arr[i][0] = i;
//arr[i][1] = i+10;
arr[0][i] = i;//switch indices
arr[1][i] = i+10;//switch indices
}
}
}
// declare and fill a simpler dynamic array
int *tarr = malloc(sizeof(int) * 10);
for (int i=0; i<10; i++)
tarr[i] = i*2;
try_by_reference(&tarr);
//try_by_reference(&arr); <-- this gets warning
//pass address of each pointer to memory, one at a time
try_by_reference(&(arr[0]));
try_by_reference(&(arr[1]));
//To prevent UB from calling free on an already freed pointer
//test before calling free.
if(arr[0]) free(arr[0]);//need to free each of two pointers to memory
if(arr[1] free(arr[1]);//...
if(tarr) free(tarr);
return 0;
}
Reference regarding why set pointer to NULL after freeing. If the call to realloc() fails, thus resulting in freeing the original pointer, setting the pointer == NULL provides a way to test before calling free() later in process, thus avoiding the potential of invoking undefined behavior (UB).
There are several ways to create varying shapes of nD arrays memory in C, some of them easier to update memory than the form int *arr[2]. But I stay with this form to illustrate specifically a way to update it. Although it requires more rigor to access elements, for a int[2][10] implemented by pointers, I prefer creating an int *arr = malloc(2*10*sizeof(*arr));. Observe the following examples for ease of use comparisons. (using a 2D like, but of different dimensions):
int arr1[3][6] = {{1,2,3,4,5,6},{7,8,9,10,11,12},{13,14,15,16,17,18}};
//same memory as
int arr2[18] = {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18}};
knowing that *(arr1 + 2*6 + 5) == arr2[2][5] = 18;
*(arr1 + 0*6 + 4) == arr2[0][4] = 5;
*(arr1 + 1*6 + 0) == arr2[1][0] = 7;
// | | |_2nd index range 0 - 5
// | |_ constant -> sizeof(arr1[0]/arr1[0][0])
// |1st index range is from 0 - 2
The same is true for dynamic memory. int **arr1 and *arr2
int **arr1 //requires 7 calls to malloc/free
int *arr2 //requires 1 call to malloc/free

Can I assign the address of shared memory to a pointer directly?

I'm trying to create a shared memory for IPC. I want to put a structure with dynamic 2D array in it into the shared memory. Here is the structure.
/* struct with 2 2D arrays. */
struct _test {
uint16_t **A;
uint16_t **B;
} test;
I know that a double pointer is not actually a 2D array and I should use a pointer to array like int (*ptr)[3], but the problem is that I can only get the size of the 2D array during runtime. So I have to declare the 2D array this way(at least what I know of).
Then I calculate the size of those two arrays in run time, say they both are 2x2 arrays, which takes 16 bytes(uint16_t is 2 byte). So I did this:
#include <sys/ipc.h>
#include <sys/shm.h>
#include <memory.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
size_t size = 16; //size of two uint16_t 2D arrays.
key_t key;
key = ftok("dev/null", 1);
int s_shm_id = shmget(key, size, IPC_CREAT|0600); //get 16 bytes of shared memory.
test *shm = (test*)shmat(s_shm_id,(const void*)0,0); //attach it.
//I want pointers in this struct to point at shared memory.
test *ptr = malloc(sizeof(test));
//Array A starts at the beginning of shared memory.
ptr -> A = (uint16_t **)shm; //My main confusion is here. Is this right?
int i;
for(i=0; i<2; i++)
ptr->A[i] =(uint16_t *)((uint16_t *)ptr->A + i*2);
//Array B starts right after A.
ptr -> B = ptr -> A[i-1] + 2;
for(i=0; i<2; i++)
ptr -> B[i] = (uint16_t *)((uint16_t *)ptr->B + i*2);
}
I understand this is basically wrong, I got segfault, but how? What a pointer needs is an address to point at, since I have already created a space(using shmget), why can't I make a pointer to point at it? Thanks for any feed back in advance!
What you are after are "jagged" or "scattered" arrays, not "linear" arrays. A scattered 2D-array in fact is not one array, but 1+N arrays, with N being the dimension of the 2D-matrix you are after.
The code you show misses to allocated this 1 array inside "1+N".
Assuming you successfully allocated enough memory to hold two 2D arrays with dimension N of uint16_t, that is 2 * N*N * sizeof (uint16_t) bytes, then the code to prepare the access to this memory might look like this (error checking left out for readability):
void * p = ... /* Allocate memory here; does not necessarily needs to be SHM. */
uint16_t ** A = malloc(N * sizeof *A);
for (size_t i = 0; i < N; ++i)
{
A[i] = ((uint16_t*) p) + i*N;
}
uint16_t ** B = malloc(N * sizeof *B);
for (size_t i = N; i < 2*N; ++i)
{
B[i - N] = ((uint16_t*) p) + i*N;
}
/* Access A[0 .. N-1][0 .. N-1] and B[0 .. N-1][0 .. N-1] here ... */
Placing A and B inside a struct which in turn is allocated dynamically is left to you as an exercise.
Accessing the arrays' elements is done straight forward: A[0][0] accesses the 1st array's 1st row's 1st element.
For clarity the same code for NxM arrays
uint16_t ** A = malloc(N * sizeof *A);
for (size_t i = 0; i < N; ++i)
{
A[i] = ((uint16_t*) p) + i*M;
}
uint16_t ** B = malloc(N * sizeof *B);
for (size_t i = N; i < 2*N; ++i)
{
B[i - N] = ((uint16_t*) p) + i*M;
}

Strange behavior while filling dinamically allocated 2D char array in C

I need to create a program that plays the game Hex on a 14x14 board.
So I created, allocated and filled the board with '-' (our pattern for empty spaces).
When I try to print the board's coordinates, I don't always get '-' but some random characters.
Also, if I try to printf array[i][j] on the createBoard function after the line "board[i][j] = '-';" I get a segmentation fault right after it prints tab[8][0].
What is causing this and how can I fix it?
My code:
#include <stdio.h>
#include <stdlib.h>
char **createBoard()
{
/*Allocates a 14x14 matrix and fills it
*with '-' to create the board.*/
int i, j;
char **board;
board = malloc(14);
if (!board) exit(1);
for (i = 0; i < 14; i++){
board[i] = malloc(14);
if (!board[i]) exit (1);
for (j = 0; j < 14; j++)
board[i][j] = '-';
}
return board;
}
int main()
{
int i, j;
char **board = createBoard();
for (i = 0; i < 14; i++)
for (j = 0; j < 14; j++)
printf("tab[%d][%d]: %c\n",i, j, board[i][j]);
return 0;
}
For starters it is not clear why you don't want to declare an array instead of allocating dynamically numerous one-dimensional arrays.
As for the code then this memory allocation
board = malloc(14);
is invalid. You have to write
board = malloc( 14 * sizeof( char * ));
Also you should free all the allocated memory in the reverse order relative to its allocation before the program ends.
Take into account that it is always better to use named constants instead of magic numbers. At least you could write either
#define N 14
before main
or
const int N = 14.
and use the variable N everywhere where you are using magic number 14.
By the way according to the C Standard function main without parameters shall be declared like
int main( void )
The variable *board is a pointer, but you only allocate one byte for each array element, which should be
#define DIM 14
board = malloc(DIM * sizeof *board);
Following that up with the second allocation
board[i] = malloc(DIM * sizeof **board);
This also allows (a) that the dimension 14 is hard coded in only one place in the program and (b) the allocation will survive if you later make the board's element a different type, for example a struct, as the program develops.

Segmentation fault when using malloc for 2D array

I create a 2-D array using malloc. When I use printf to print the array element in for loop, everything is fine. But when I want to use printf in main, these is a Segmentation fault: 11.
Could you please tell me what the problem with the following code is?
#include <stdlib.h>
#include <stdio.h>
void initCache(int **cache, int s, int E){
int i, j;
/* allocate memory to cache */
cache = (int **)malloc(s * sizeof(int *)); //set
for (i = 0; i < s; i++){
cache[i] = (int *)malloc(E * sizeof(int)); //int
for(j = 0; j < E; j++){
cache[i][j] = i + j;
printf("%d\n", cache[i][j]);
}
}
}
main()
{
int **c;
initCache (c, 2, 2);
printf("%d\n", c[1][1]); // <<<<<<<<<< here
}
Since your cache is a 2D array, it's int**. To set it in a function, pass int***, not int**. Otherwise, changes to cache made inside initCache have no effect on the value of c from main().
void initCache(int ***cache, int s, int E) {
int i, j;
/* allocate memory to cache */
*cache = (int **)malloc(s * sizeof(int *)); //set
for (i = 0; i < s; i++) {
(*cache)[i] = (int *)malloc(E * sizeof(int)); //int
for(j = 0; j < E; j++){
(*cache)[i][j] = i + j;
printf("%d\n", (*cache)[i][j]);
}
}
}
Now you can call it like this:
initCache (&c, 2, 2);
You changed a local variable, which won't effect the local variable c in main.
If you want to allocate in the function, why pass a variable? Return it from the function.
int **c = initCache(2, 2);
You could use a return, or else a *** as suggested by others. I'll describe the return method here.
initCache is creating and initializing a suitable array, but it is not returning it. cache is a local variable pointing to the data. There are two ways to make this information available to the calling function. Either return it, or pass in an int*** and use that to record the pointer value.
I suggest this:
int** initCache(int **cache, int s, int E){
....
return cache;
}
main()
{
int **c;
c = initCache (2, 2);
printf("%d\n", c[1][1]); <<<<<<<<<< here
}
====
Finally, it's very important to get in the habit of checking for errors. For example, malloc will return NULL if it has run out of memory. Also, you might accidentally as for a negative amount of memory (if s is negative). Therefore I would do:
cache = (int **)malloc(s * sizeof(int *));
assert(cache);
This will end the program if the malloc fails, and tell you what line has failed. Some people (including me!) would disapprove slightly of using assert like this. But we'd all agree it's better than having no error checking whatsoever!
You might need to #include <assert.h> to make this work.

Resources