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

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".

Related

How can I delete the first zero(s) in a string? (Without using atoi) [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 3 years ago.
Improve this question
I was making a script that is calculating the additions between two natural numbers which decimal lengths should be smaller or same with 10000, and printing a result of the sum.
Of course, there ain't any variable type that can hold a integer which length is 10000 in C.
So, I made the program by utilizing the simple additions' calculating logic that all we learn in a school when we were young. And also, I just should use strings to get those gigantic numbers.
But some results were starting with zero. I knew why did the zero appeared there, but I did prefer to have a result that is like "1234", not "01234". By the way, all other stuffs were perfect.
I needed a function that gets input as string, and erases a single zero starts with a string if it exists.
And could you make it instead of me, please? You should probably consider that the strings we will deal with can have such a length that is smaller or same with 10000.
Maybe this:
char * f( char * str )
{
while ( *str == '0' && str[1] )
str++; // skips all zero-s when it is not last character in string
return str;
}

I Want to Clarify whether Following answer Correct or Not? [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 5 years ago.
Improve this question
int sum(int A[], int n)
{
int sum = 0, i;
for(i = 0; i < n; i++)
sum = sum + A[i];
return sum;
}
'n*2' bytes of memory to store array variable 'a[]'
2 bytes of memory for integer parameter 'n'
4 bytes of memory for local integer variables 'sum' and 'i' (2 bytes
each)
2 bytes of memory for return value.
Total space Needed = 2n + 8
let assume c compiler takes 2 bytes for store integer value
I want to know whether above calculated total space answer is correct or not?
I have doubt in return statement because i first allocate memory to sum variable and sum is return last so i need to no whether return sum statement needed memory allocation.
ASSUMING -> the posed question was about how much stack space this function will require:
Well, the A[] parameter is not an array; it's a pointer to the first element of the array, so that's sizeof(int*), not n * sizeof(int).
Whether you need space for the return value depends on whether your environment returns integers in CPU registers, or pushes them onto the stack. If on the stack, then yes, you need to allow for that space.
ASSUMING -> the posed question was about BigO space complexity
Caveat: How you calculate space complexity for an algorithm depends LARGELY on the programming language and / or hardware environment. Contrast this with time complexity, which is mostly language / hardware agnostic. Be advised that most examples for space complexity on the web make some pretty bald assumptions.
For example, the A[] parameter in this example is almost always assumed to consume the space required for every element in the array. In C, and languages that pass object references, this is simply not true. In some of the web examples, this is mentioned in a footnote; in others, not at all.
So, for this post, the answer for BigO space complexity is -> It Depends. It could either be O(1) or O(n), depending on who's asking and where it's expected to run.

Runtime error when running my code [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 6 years ago.
Improve this question
When I compile my C codes sometimes I get this error message.
Mycode.exe has stopped working..
A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution available.
My C code :
#include<stdio.h>
main(){
char a;
a="S";
printf("%s",a);
}
So what is the reason for this problem?
Syntax error, Runtime error or another reason?
When you invoke printf with %s it means that printf will start printing at the given address and end when a null terminator is reached, because you are giving printf a char and not a pointer to a char, it tries to use the value written in a to start printing from.
a is a char taking up a space of one Byte while an address is 8 Bytes in a 64 bit system, so basically printf takes the value in 'a' and the the next 7 Bytes(which are random 'garbage') and tries to use it as an address to stop printing.
that is why it sometimes works as you said, sometimes those random addresses are fine to start printing from, but sometimes they are addresses that you are not authorized to access like areas of memory used by the OS or kernel.
to solve the problem you need to make a a char * and not a char, and assign it with a string.
Change your code to
#include<stdio.h>
int main()
{
char a;
a='S';
printf("%c",a);
return 0;
}
and it will work fine.

C Realloc Memory [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 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

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