C Realloc Memory [closed] - c

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 6 years ago.
Improve this question
I need to memorize how much memory I allocated with realloc().
Help me
if(!array)
array=(Type*) calloc(1,sizeof(Type));
else
array=(Type*)realloc(array,(cont+1)*sizeof(Type));
array[cont].setName(....);
cont++;
It doesn't work: after firt insert, it say: Access violation
I initialized the cont = 0 in the constructor of my class and freed memory in the destructor.

See the comments added to your code:
int count=0;
if(!array)
array=(Type*) calloc(count,sizeof(Type*); // Problem:
// missing )
// use sizeof(Type)
// calling calloc with count being zero
// so you do not allocate any memory
// use 1 instead of count
array[c].setName(EditName->Text);
c++;
count++;
array=(Type*)realloc(array,count*sizeof(Type*)); // Problem:
// use sizeof(Type)
so it should look:
int count=0;
if(!array)
array=(Type*) calloc(1,sizeof(Type));
array[c].setName(EditName->Text);
c++;
count++;
array=(Type*)realloc(array,count*sizeof(Type));
The variable c must be initialized to zero before running this code
Likewise array must be nullptr before running this code
EDIT
There seem to be one more problem if you intend to run this code several times (which I assume you do).
This line:
array=(Type*)realloc(array,count*sizeof(Type));
^^^^^
Don't use count here as you always sets count to zero
The line shall be:
array=(Type*)realloc(array,c*sizeof(Type));
In general there seems to be no real use of count

Related

strcpy() function is enterning into infinite loop [closed]

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 4 years ago.
Improve this question
hai i am having a problem with strcpy() function. this is related to embedded c programing.
the following is a part of code used in my project. Basic idea is to copy string(name) to an array _Items whose memory is dynamically allocated
char *_Items[100];
unsigned char contactname[36];
Memset(name,0,36);
Memset(_Items, 0, sizeof(_Items));
for(count=0; count<10 ; count++)
{
_Items[count] = (char*)malloc((strlen((char*)name)+1)*sizeof(char));
strcpy(_Items[count], (char*)name);
}
....
...function body
....
free(_Items);
In the first time call of the function the code is working fine, but in the second time call call of the function strcpy() func is entering an infinite loop.
I am not able to understand what the exact problem is. Please help me out.
did you malloc anything here ?:
char *_Items[100];
No. So why are you calling free(_Items); ?
did you malloc anything here?:
for(count=0; count<10 ; count++)
{
_Items[count] = (char*)malloc((strlen((char*)name)+1)*sizeof(char));
Yes. So why don't you call free for each item in the loop?
Calling free(_Items) tells the system to free some memory that hasn't been allocated using malloc, which is _undefined behaviour, and breaks the rest of the execution, can be anywhere (that's the "fun" of it).
Rewrite your free process:
// allocate
for(count=0; count<10 ; count++)
{
_Items[count] = malloc((strlen((char*)name)+1));
strcpy(_Items[count], (char*)name);
}
....
...function body
....
for(count=0; count<10 ; count++)
{
free(_Items[count]);
}

Cannot change number in array into one I want [closed]

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 4 years ago.
Improve this question
I have little problem here. Ever since I used srand command I no longer get output I want.
I have to create program that will create array not matter how long.. I chose 5. Then it has to create random numbers into it and 5th number in it has to be 0 and then it has to count all five numbers together. I was sucessful and I did even use some printfs to check if arr[5] is zero. It is. In output I receieve this: 5random numbers (that ones that were created into array) 0 (to check if command where i set arr[5] really set it to zero and result which only count all 5random numbers together but without changing 5th arr into 0. Any ideas why? Thanks!
Code looks like this:
#include <stdio.h>
#include <time.h>
main()
{
srand(time(NULL));
int result,i;
int arr[5];
for (i=0;i<5;i++)
{
arr[i] = rand() % 10+1;
printf("%d ",arr[i]);
}
arr[5]=0;
printf("\n");
printf("%d\n",arr[5]);
i=0;
for(;i<5;i++)
{
result +=arr[i];
}
printf("%d\n",result);
printf("%d\n",arr[5]);
}
The declaration int arr[5] gives an array with five elements numbered from 0 to 4 inclusive. Accessing the 6th element, arr[5], is undefined.
If you want five elements and a "sentinel" (the zero marker), you could define arr as
int arr[6];
You should probably also initialize result to 0 otherwise its value is undefined since it's a local variable (in fact, the meaning of the whole program is, strictly speaking, undefined in this case).

I can't understand an error in a function [closed]

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 5 years ago.
Improve this question
This function make a strange error after using it several times and I really can't understand the reason behind it.
char *get_range(char *str,int min,int max){
char *_res=(char *)malloc(sizeof(str));
int cur=0;
while (min<max){
_res[cur]=str[min];
min++;
cur++;
}
return _res;
}
The problem is that after using this function several times, the output comes with additional chars and I don't understand why.
Notice: The additional chars are allway used returned by the function beffor
char *_res=(char *)malloc(sizeof(str));
is wrong. sizeof(str) is measuring the size of a char pointer. This is either 4 or 8 (typically) depending on your system (32 or 64 bit).
You need
char *_res=(char *)malloc(strlen(str) + 1);
strlen returns the number of characters in the string, and you need to add 1 for the terminating 0;
Second you have to add a terminating zero at the end, do:
_res[cur] = '\0';
before returning

why malloc is returing o as default in gcc compiler? [closed]

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
Hi i new learn here please explain below question i m learning on my own from many days i do have some dout with malloc function .please help i know this site it not for beginners but i couldn't get alternative way to find the solution
1) p=malloc(0) // what will it return ?when i calculate size using sideof operator it throw 4 byte?
2) int *p=malloc(4) // when i scan string it throw 0 why sir?
3) *p=2 // while p is store in heap
scanf("%d",*p)//why *p is not possible to scanf here *p why p only?
4) int *p=(int*)malloc(20*sizeof(int))
for(i=0;i<5;i++)
p[i]=i+1;
free(p);
//now after free i am still get same previos value.. why not garbage coz malloc default value is garbage?
5) int main()
{
int *p;
p=(int*)malloc(4);
printf("%d\n",*p); // even here i am getting 0 why nt garbage?
}
Thank you sir
"Freeing" means "making available for allocation again". There is no automatic deleting / overwriting of memory contents because it would negatively impact performance. If you want the area to be set to a value, you have to do it yourself before you call free(). That would be bad practice in release code, though (for anything else but data security reasons).
The same is true when allocating the memory: It does not get set to any specific value, but contains what it happened to contain previously. If you want it to be initialized to zero, use calloc(). If you want to set it to a specific other value, use memset() after you allocated it. Again, consider that this has performance implications, and is usually not necessary.
As for your last question, "%d" is for signed integers. For unsigned, use "%u".

Crash when trying to make an array overrun [closed]

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
I read this paragraph in c the complete reference book
C has no bounds checking on arrays. You could overwrite either end of
an array and write into some other variable's data or even into the
program's code. As the programmer, it is your job to provide bounds
checking where needed. For example, this code will compile without
error, but it is incorrect because the for loop will cause the array
count to be overrun.
#include <stdio.h>
int main(){
int count[10], i;
/* this causes count to be overrun */
for(i=0; i<15; i++) count[i] = i;
for(i=0; i<15; i++) printf("%d ",count[i]);
return 0;
}
and when I try the code it gives me
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
And then a run time error was displayed on the screen. The error was
array.exe has stopped working
My question is : What is the type of that error? And does it mean that my IDE checks the bounds of the array?
C doesn't check array idexing, it does only simple pointer-arithmetic. That is, the standard defines the operation array[i] as array + i.
Depending on the resulting memory address of that computation, many things can occur:
The address points to the location of a local variable of the function: You modify the local variable. For example:
int main()
{
int array[10];
int a = 0;
array[11] = 22;
printf(a%i,a); /* Prints 22 */
}
Remember that the point here is that buffer overrun has undefined behaviour. My example could not work, because the compiler is free to reorder the variables layout during compilation, for memory-aligment and optimising purposes.
The address points to the location of a global variable (Thats a very big indexing/jump, but can occur): The effect is the same as in the local variable case.
The address points to the location where the subroutine stores the return address: Many architectures stores the return address of a function in a register, but if the architecture stores it in the stackframe of the function... WOW. TRY TO DEBUG THAT!!! :)
The address goes out of the memory space of the process: Modern operative systems always check memory accesses to prevent this, so when this happens the OS kicks you in the ass and throws an exception.
Finally note that things are only applicable in release compilation. In debug mode the compiler adds a lot of code to check this kind of things to throw (Provide) a comprehensible and easy-debuggeable exception.
For example: When allocating dynamic arrays, windows debug-heap first fills the memory space that will be used with a flag which says that memory space is ready to use, but it doesn't contains any data: Thats the hexspeak 0xBADF00D. After this, malloc retrieves the memory location, adding hexspeaks around the array to provide bounds checking.
See this article for a complete explanation.
The moment the first loop reaches i=10, you enter the realm of undefined behaviour (since you're writing past the end of count). From that point on, anything can happen.
Your IDE had nothing to do with it. The OS killed your program because it tried to access memory that didn't belong to it.
This type of error is usually known as an access violation.
That's fine - and the point of the article you have read...
What you are supposed to do is limit the for loop so that it only runs from 0 to 9.
Or, if you really need 15 items, expand the array to take them...

Resources