memcpy on two-dimensional array - c

I am wondering if I am using the memcpy function right.
So I have a two-dim. array of strings, and when I try to fill them valgrind tells me
==825== Invalid write of size 8
==825== at 0x344B8E: _platform_memmove$VARIANT$Unknown (in /usr/lib/system/libsystem_platform.dylib)
==825== by 0x1C4D74: __memcpy_chk (in /usr/lib/system/libsystem_c.dylib)
==825== by 0x100001328: generate_test_data (check_generate_test_data.c:4120)
==825== by 0x100000CA6: main (check_generate_test_data.c:137)
==825== Address 0x100030a00 is 0 bytes after a block of size 32 alloc'd
==825== at 0x47F1: malloc (vg_replace_malloc.c:302)
==825== by 0x100000FBB: generate_test_data (check_generate_test_data.c:4095)
==825== by 0x100000CA6: main (check_generate_test_data.c:137)
int i;
char **test;
int total = 4;
int elements = 11;
test = malloc(sizeof(char**)* total);
for (i=0; i < total; i++) {
// char *to_fill --//is filled with a method
//
test[i] = malloc(sizeof(char*) * elements; // <== here is where compiler complains
memcpy(&test[i], &to_fill, strlen(to_fill); // <== here is where valgrind complains
}
When I change it to:
&test[i][0]
then the strings in test stay empty :S.. I also tried to remove the & of to_fill but with this my program just crashes.. I have no Idea what I am doing wrong here.
I changed all of the suggestions but the same error of valgrind appears, I even tried to put a constant char array into to_fill but still:
int i;
char **test;
char *to_fill;
int total = 4;
int elements = 11;
test = malloc(sizeof(char*)* total);
to_fill = malloc(sizeof(char)* 100);
to_fill[0] = '\0';
for (i=0; i < total; i++) {
//to_fill = method_to_fill_it();
strncpy(to_fill, "example", 7);
to_fill[7] = '\0';
test[i] = malloc(sizeof(char*) * elements;
memcpy(&test[i], &to_fill, strlen(to_fill); // <== here is where valgrind complains
to_fill[0] = '\0';
}

Your memcpy statement is wrong, you don't need to dereference a char pointer which holds the address as it's value. Do this instead:
memcpy(test[i], to_fill, strlen(to_fill));
When you do:
memcpy(test[i], &to_fill, strlen(to_fill));
the memory address where to_fill is stored is passed to the function.
What you want to pass is the memory to which to_fill, the pointer, points to.

Related

realloc invalid next size for array

Hello I keep getting invalid next size when using realloc to allocate more memory to an array which im trying to add 100,000 numbers too. I dont know why because im not understanding why it wont work. My code is here below.
int main()
{
printf("starting");
int i;
int *bubbleSortArray = (int *)malloc(sizeof(int));
int numberOfElements = 0;
int randomNumber;
srand(time(NULL));
int j;
for (int j = 0; j <= 100000; j = j +1)
{
randomNumber = rand();
if(numberOfElements != 0)
{
bubbleSortArray = (int *) realloc(bubbleSortArray, numberOfElements * sizeof(int));
}
bubbleSortArray[numberOfElements] = randomNumber;
numberOfElements = numberOfElements + 1;
}
}
In the statement you need to write at least like
bubbleSortArray = (int *) realloc(bubbleSortArray, ( numberOfElements + 1 )* sizeof(int));
Otherwise this statement
bubbleSortArray[numberOfElements] = randomNumber;
invokes undefined behavior.
Also you need to use an intermediate pointer to store the return value of the call of realloc because the function can return a null pointer. In this case the previous value stored in the pointer bubbleSortArray will be lost and you will not have an access to the already allocated memory.
So it would be better to write
int *tmp = (int *) realloc(bubbleSortArray, ( numberOfElements + 1 )* sizeof(int));
if ( tmp != NULL )
{
bubbleSortArray = tmp;
}
else
{
// some other code
}
Pay attention to that these declarations
int i;
int j;
are redundant because the declared variables are not used.
Oh, this is kind of scary. I'm not sure why you're not allocating enough space up front. But this code is going to realloc 100,000 times, which is an insane thing to do. Do you know what realloc does under the hood? I'll explain.
First, it does a NEW alloc of the amount of data. So the first time you loop, numberOfElements is zero, and you use your malloc'd space. But the second time it allocates space for 2 integers, then 3 integers, then 4, et cetera.
So it allocates 8 bytes. It remembers how much it allocated last time (4 bytes -- the size of an int on most systems), and it then does a memcpy of that much space.
Then it memcpy's 8 bytes. then it memcpy's 12 bytes, and so on and so on.
Bad, bad, bad.
What most people do is keep track of two values -- the amount of space allocated (capacity) and the amount used (count or numberOfElements).
So it looks something like this:
int capacity = 16;
int *bubbleSortArray = (int *)malloc(capacity * sizeof(int));
...
if (numberOfElements >= capacity) {
// Increase capacity by whatever means you want.
// You can double it. Or you can:
capacity += 16;
bubbleSortArray = (int *) realloc(bubbleSortArray, capacity * sizeof(int));
}
Ah, and as I cut & pasted your code, I see that you used numberOfElements. So you were consistently undersizing your realloc by 1, anyway.

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

No access to dynamically allocated array of 2 dimensions [duplicate]

This question already has an answer here:
Dynamic memory access only works inside function
(1 answer)
Closed 3 years ago.
I'm experimenting with the dynamic memory allocation of variable sized arrays. The function "ft_ultimate_range" seems to work, however, a problem arises when I try to access and print the values of each array's array. It signals either segmentation fault: 11, when compiled with GCC, or "subscripted value is neither array nor pointer nor vector" with [http://pythontutor.com/c][1]. I understand that this has to do with the use- or abuse of pointers... ehm
// allocate a grid of [n][n] with numbers ranging max-min
int *ft_ultimate_range(int **range, int min, int max)
{
int len, *ptr;
int count = min;
len = max - min;
ptr = range;
// allocate memory **arr
range = malloc(len * sizeof * range);
for(int i = 0; i < len; i++) {
range[i] = malloc(len * sizeof * ptr);
}
// assign values to allocated memory location
for(int i = 0; i < len; i++) {
for(int j = 0; j < len; j++) {
range[i][j] = count++;
}
count = min;
}
// free memory **range
for(int i = 0; i < len; i++) {
free(range[i]);
}
free(range);
return ptr;
}
int main()
{
int n;
n = 6 - 3;
int **ptr, *arr;
arr = ft_ultimate_range(ptr, 3, 6);
// print
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
printf("%d", ptr[i][j]);
}
}
return 0;
}
...a little pointer in the right direction would be very much appreciated.
Well, it obvious you are quite lost regarding how to return an allocated grid (pointer-to-pointer-to-int) from ft_ultimate_range() to main().
To begin, you do not need to pass range as a parameter to ft_ultimate_range(). Instead, make the return type int ** and declare int **range within ft_ultimate_range() and then allocate len pointers, and then allocate len integers per-pointer, assign the values and then return range and assign it to arr in main(), e.g.
#include <stdio.h>
#include <stdlib.h>
/* allocate a grid of [n][n] with numbers ranging max-min */
int **ft_ultimate_range (int min, int max)
{
int len = max - min,
**range = NULL,
count = min;
/* allocate len pointers */
range = malloc (len * sizeof * range);
if (!range) { /* validate EVERY allocation */
perror ("malloc-range");
return NULL;
}
/* allocate len int per-pointer */
for (int i = 0; i < len; i++) {
range[i] = malloc (len * sizeof *range[i]);
if (!range[i]) { /* validate alloation */
perror ("malloc-range[i]");
while (i--) /* free previously allocated rows */
free (range[i]); /* free pointers */
free (range);
return NULL;
}
}
/* assign values to allocated memory location */
for(int i = 0; i < len; i++) {
for(int j = 0; j < len; j++) {
range[i][j] = count++;
}
count = min;
}
return range;
}
(note: you MUST VALIDATE EVERY ALLOCATION...)
In main(), you don't need ptr, all you need is the int** pointer you will assign the return from ft_ultimate_range() to, e.g.
int main (void) {
int n = 6 - 3;
int **arr;
arr = ft_ultimate_range (3, 6);
if (!arr) /* validate return */
return 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf (" %d", arr[i][j]);
}
putchar ('\n');
free (arr[i]);
}
free (arr);
return 0;
}
(note: similarly, you must validate the return of ft_ultimate_range() before blindly looping through the values (that will not be there if an allocation failed)).
Example Use/Output
$ ./bin/alloc_a_grid
3 4 5
3 4 5
3 4 5
Memory Use/Error Check
In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.
It is imperative that you use a memory error checking program to insure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.
For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.
$ valgrind ./bin/alloc_a_grid
==29026== Memcheck, a memory error detector
==29026== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==29026== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==29026== Command: ./bin/alloc_a_grid
==29026==
3 4 5
3 4 5
3 4 5
==29026==
==29026== HEAP SUMMARY:
==29026== in use at exit: 0 bytes in 0 blocks
==29026== total heap usage: 4 allocs, 4 frees, 60 bytes allocated
==29026==
==29026== All heap blocks were freed -- no leaks are possible
==29026==
==29026== For counts of detected and suppressed errors, rerun with: -v
==29026== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Always confirm that you have freed all memory you have allocated and that there are no memory errors.
Look things over and let me know if you have further questions.
Here:
int **ptr, *arr;
arr = ft_ultimate_range(ptr, 3, 6);
ptr is NULL / uninitialised now. You cant allocate of this. malloc must be before call a function ft_ultimate_range. Here: printf("%d", ptr[i][j]); is NULL[i][j].
And you free **ptr in function ft_ultimate_range.
Hope this help.
int **ptr, *arr;
ptr is uninitialised at this point. It's value is indeterminate.
arr = ft_ultimate_range(ptr, 3, 6);
Passing an uninitialised value to a function is always wrong. If you hope the function will initialise it, you are mistaken. Read on pass by value.
ptr = range;
This assignment is wrong. You should have received a compiler warning about it. If you did not, upgrade your compiler ASAP. Never ignore warnings. Toying with a program that compiles with warnings is a waste of time.
for(int i = 0; i < len; i++) {
free(range[i]);
}
free(range);
At this point, every pointer in the program is invalid. Dereferencing them is undefined behaviour.
It isn't at all clear what your program is supposed to return. You are not using the return value anyway.
I suggest changing the signature of your function to this:
int** ft_ultimate_range(int min, int max)
Try to fit whatever you are trying to do in this mold.

how to manually concat a char **args to char *args

so I'm trying to write a function that concats a char**args to a char*args
What I have so far is":
char *concat(char **array)
{
int size = 0;
int i=0;
int j=0;
int z=0;
while (array[i]!=NULL)
{
printf(" %s \n", array[i]);
size = size + sizeof(array[i])-sizeof(char); //get the total size, minus the
//size of the null pointer
printf("%d \n",size);
i++;
}
size = size+1; //add 1 to include 1 null termination at the end
char *newCommand = (char*) malloc(size);
i=0;
while(i<sizeof(newCommand))
{
j=0;
z=0;
while (array[j][z]!='\0')
{
newCommand[i] = array[j][z];
i++;
z++;
}
j++;
}
newCommand[sizeof(newCommand)-1]='\0';
return newCommand;
}
this doesn't seem to work. Anyone know what's wrong?
I'd do it like this (untested):
int size = 0;
int count = 0;
while (array[count]) {
size += strlen(array[i]);
count++;
}
char *newCommand = malloc(size + 1);
char *p = newCommand;
newCommand[0] = 0; // Null-terminate for the case where count == 0
for (int i = 0; i < count; i++) {
strcpy(p, array[i]);
p += strlen(array[i]);
}
First, your size calculation was wrong. You wanted the size of the strings, but sizeof(array[i]) gives you the size of a single element in your array which is a pointer and thus 4 (32-bit) or 8 (64-bit). You need to use strlen instead.
Next, your manual copying was also off. It's easier to do it with a moving pointer and strcpy (which is to be avoided normally but we've calculated the sizes with strlen already so it's OK here). The use of strcpy here also takes care of null termination.
Main issue is that you keep using sizeof() with a pointer argument, whereas I think you are trying to get the size of the corresponding array.
sizeof() can only give you information that's available at compile time, such as the sizes of raw types like char and int, and the sizes of arrays with a fixed length such as a char[10]. The sizes of the strings pointed to by a char* is only computable at run time, because it depends on the exact values passed to your function.
For sizeof(newCommand) you probably need size, and for sizeof(array[i]), you probably need strlen(array[i]).

Resources