Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I want to give a random size to pointer and I want to add some elements to the pointer. I want to give place to the pointer enough size. For example, if I have 10 elements in pointer, I want to give place 40 byte to pointer. But when I looked to my code, initially I gave so much size for the element.
I want to see as an output:
67
11
64
7
67
11
64
7
23
81
88
35
12
5
7
The size of memory=40
#include <stdio.h>
#include <stdlib.h>
int main() {
int *k;
int i=0,j=0,t=0;
int array[20]={67,11,64,7};
k=malloc(5*sizeof(int));
k=array;
for(i=0;i<4;i++){
printf("%d\n",k[i]);
}
k=realloc(k,50*sizeof(int));
k[4]=23;
k[5]=81;
k[6]=88;
k[7]=35;
k[8]=12;
k[9]=5;
k[10]=7;
for(j=0;k[j]!='\0';j++){
printf("%d\n",k[j]);
}
k=realloc(k,(j+1)*sizeof(int));
for(t=0;k[t]!='\0';t++){
printf("%d\n",k[t]);
}
printf("the size of the memory=%d \n",j*4);
printf("the size of the memory=%d \n",t*4);
return 0;
}
You can't resize an automatic variable like array which is what you are trying to do since you do k=array; (and leak the memory previously allocated).
You can copy the data from array into the allocated memory pointed out by k instead:
int array[20] = {67, 11, 64, 7};
int *k = malloc(sizeof array);
memcpy(k, array, sizeof array);
The loop condition you use is a tad confusing though:
for (j = 0; k[j] != '\0'; j++)
I suggest comparing with 0 instead.
The "the size of the memory" that you print out at the end is however not accurate. The size of the allocated memory at the end is (j+1)*sizeof(int), that is, 12 * sizeof(int), since k[11] is the first element being 0.
A word of caution is also in place: Your program currently has defined behavior because the array does contain 0:s in the positions [11, 19]. Just be aware that the extra memory allocated by realloc contains indeterminate values, so had your original array been only 11 elements big, you had read those indeterminate values when you compare with \0 (or preferably 0) and you would never know what the result would be. It could continue searching for \0 out of bounds.
Note: Don't forget to free(k); when you're done with it.
Related
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 2 years ago.
Improve this question
Computer Systems: a Programmer's Perspective says:
1 /* Illustration of code vulnerability similar to that found in
2 * Sun’s XDR library.
3 */
4 void* copy_elements(void *ele_src[], int ele_cnt, size_t ele_size) {
5 /*
6 * Allocate buffer for ele_cnt objects, each of ele_size bytes
7 * and copy from locations designated by ele_src
8 */
9 void *result = malloc(ele_cnt * ele_size);
10 if (result == NULL)
11 /* malloc failed */
12 return NULL;
13 void *next = result;
14 int i;
15 for (i = 0; i < ele_cnt; i++) {
16 /* Copy object i to destination */
17 memcpy(next, ele_src[i], ele_size);
18 /* Move pointer to next memory region */
19 next += ele_size;
20 }
21 return result;
22 }
The function copy_elements is designed to copy ele_cnt data
structures, each consisting of ele_ size bytes into a buffer allocated
by the function on line 9. The number of bytes required is computed as
ele_cnt * ele_size.
Imagine, however, that a malicious programmer calls this function with
ele_cnt being 1,048,577 (2^20 + 1) and ele_size being 4,096 (2^12)
with the program compiled for 32 bits. Then the multiplication on line
9 will overflow, causing only 4,096 bytes to be allocated, rather than
the 4,294,971,392 bytes required to hold that much data. The loop
starting at line 15 will attempt to copy all of those bytes,
overrunning the end of the allocated buffer, and therefore corrupting
other data structures. This could cause the program to crash or
otherwise misbehave.
I was wondering how to change the code to have no vulnerabilities due to arithmetic overflow?
Thanks.
From a mathematical viewpoint you want to check (size_t)-1 < ele_cnt * ele_size. However you can't do that in code because of the overflow. You can instead apply some algebra to avoid the overflow. You also want to first check that both values are positive:
if ((ele_size == 0) || (ele_cnt <= 0) || ((size_t)-1 / ele_size < ele_cnt)) {
return NULL;
}
Regarding the cast (size_t)-1, because size_t is an unsigned type the conversion is well defined and evaluates to the largest value that can be stored in a size_t.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
In c ,How much memory consume an array,That is only one single array
ie,int a[0]; or char a[0];
I want to know it when the program writes on a paper ,not at program running on compiler
Here I cant use sizeof function , my compiler is avrgcc ,
In the part of my program some where I require an array of int a[13];only
or Instead of int a[13]; an int a[3]; along with an integer type additionally ie, int i.
specifically I require
if i require 13 integer array or 4 integer array along with an integer variables.
which is less memory used
The size of an array is the sum total of the size of each element in the array.
For example,
if the array size is 5
the array element (type) size is 4 bytes
The whole array would consume (size * sizeof individual element), i.e., in this case 5 * 4 == 20 bytes.
This is irrespective of the usage, i.e., how many elements you actually plan to use.
FWIW, a 0-size/ 0-length array is non-standard. It's a gcc extension for a particular purpose (before the addition of flexible array member as a standard) that supports a 0-sized array, but you better not reply on it.
An int (integer) type variable has a size of 2 bytes, a char has 1 byte. In an array the size of array multiplied by size of variable according to its type will give you the size of the array.
And you can use the sizeof also.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How can I pass an array into a function and retain information about its length without passing the length separately?
[self Q&A - better answers than mine below]
In C, arrays can't be passed entirely to a function and hence it is not possible. When you pass an array name then it decays to pointer to the first element. Using sizeof operator would not help you in any way because it will give you the size of pointer.
Either you pass the size of array to the function or use a sentinel value at the end of array.
#include <stdio.h>
int size(int *a)
{
int count = 0;
while(*a++ != -1)
count++;
return count + 1;
}
int main(void)
{
signed int a[] = { 3, 5, 7, 9, 10, -1};
printf("size of array is: %d\n", size(a));
}
AFAIK If you pass an array as a pointer, there is no way to know its length in C. The length has to be provided by the caller.
Summing things up:
either provide a sentinel value that marks the end of the array
or pass the size of the array to the callee
The only two methods that actually work.
You can pass the length separately, like many do. Another perhaps impractical way is that you could pass a pointer to the array itself and retrieve the length from there.
EDIT #2: Removed the version with the global variable since it's bad practice. I'm reposting the old solution, which though rigid was less tedious and less dangerous.
EDIT #3: Replaced the original with something that at least shows how this could be useful.
#include <stdio.h>
void printArray(char (*p)[10]);
int main(void){
char p[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
printArray(&p);
return 0;
}
void printArray(char (*p)[10]){
for(int i = 0; i < sizeof (*p); i++)
printf("%d ", (*p)[i]);
printf("\n");
}
Output:
0 1 2 3 4 5 6 7 8 9
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
is there any way how to put integer sized 100 000 into 4 elements of char array? If I use sprintf or itoa, array has 6 elements. I tried to use this, but it didnt work. And is there any way how to put these 4 elements back to integer?
char *s;
int value = 100000;
*((int *)s)=value;
Note that:
int value = 100000;
char *s;
*((int *)s)=value;
dereferences uninitialized pointer s, which causes undefined behavior. You could do:
int value = 100000;
char s[4];
*((int *)&s[0])=value;
just note that this stores value in the memory block "occupied" by charr array (at memory level) unlike sprintf, which would print the value in a form of string (characters representing the number).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to prompt the user to enter a number, and then have the computer create that many arrays.
For example if the user entered the number 5, I would would want 5 integer arrays called array1[64], array2[64], array3[64], array4[64], and array5[64] to be created.
You can use array of pointers
Like following :-
int n,i;
//enter n
int **array = malloc(sizeof(int*)*n);
for(i=0;i<n;i++)
array[i] = malloc(sizeof(int)*64);
/* Do Stuffs*/
/* Free Memory */
for(i=0;i<n;i++)
free(array[i]);
free(array);
Anytime you say, "I want N variables of the same type named var1, var2, var3, ..., varN", what you really want is an array; in this case, you want an array of arrays.
Assuming that you know the second dimension at compile time (i.e., it's always going to be an Nx64-element array of int), then this is easy:
#include <stdlib.h>
...
size_t numArrs = 0;
// get numArrs from user
int (*arrs)[64] = malloc( sizeof *arrs * numArrs );
Presto - you've allocated an Nx64 array of int that you can access like any normal 2D array:
arrs[i][j] = some_value();
arrs[0] is your first 64-element array of int, arrs[1] is your second 64-element array of int, etc.