[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
Difference btw malloc and create a variable soon after?
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 57
Thread images: 3
File: c prog.png (33 KB, 512x512) Image search: [Google]
c prog.png
33 KB, 512x512
What's the difference between:

...
fscanf("%d",&n);
int array[n];
...

and:

...
int* array;
fscanf("%d",&n);
array=malloc(n*sizeof(int));
...

It's just the "legibility" (that is: a part of definitions, another for the code). Right?
>>
EDIT: scanf, not fscanf. Pardon.
>>
Fuck off pajeet
>>
>>52220939
I don't believe the first is valid C code
>>
>>52220939
The first is illegal, feeding an array a size using [] requires a compile-time constant value.

Dynamically allocating arrays in C always uses the second method.
>>
>>52221108
>>52221135

Code::Blocks compiled the fist one too.
>>
>>52221183
Code::Blocks is an IDE, not a compiler.
>>
>>52221108
>>52221135
Using gcc.
>>
>>52221189
Yeah, sorry. I wrote "using gcc" soon after.
>>
>>52220939
The first, if it was legal would allocate the array onto the stack.

The second allocates memory on the heap.
>>
>>52221405
Here is your explanation fucking indian pajeet
>>
>>52221405
Thank you.

>>52221608
I'm not indian, BTW :)
And...could you stop being a jerk, please?
>>
>>52221405
Can you advise-me a book that covers such advanced topics, please?
>>
A variable being created as in the first example is on the stack. Memory thats manually allocated with malloc (or new) is on the heap.

If you have a huge database for example, you may choose to make with malloc and keep it on the heap, and reference it by pointer as opposed to passing it around by value, on the stack
>>
>>52221678
>advanced topics
>heap and stack

just go learn ruby.
>>
>>52221678
>advanced topics
>dynamic allocation
>>
When you do
int array[n];

It creates an array on the stack.

When you
int* array = malloc(sizeof(int) * n);

It creates an array on the heap.

You NEED to learn the difference between the stack and the heap if you want to write C programs. I'm not going to teach it to you so go look it up.
>>
>>52221405
>The first, if it was legal would allocate the array onto the stack.
most times not even the stack (just a register)
>>
>>52221697
Can't I reference it if it's on the stack?
>>
>>52221722
>
sizeof(int) * n

Not him, but when you are using malloc right after declaring the pointer, isn't the sizeof unnecessary?
>>
>>52221745

stop asking questions when you have no idea what's going on. read K&R or something that teaches you the basics. you're not going to get anywhere asking random questions with no foundation. seriously, stop.
>>
>>52220939
The first one is not valid in C89.
>>
>>52221734
You can't really store an array in a register.

>>52221745
To C, they're both the same (pointers, references yadda yadda).
The important difference between stack and heap is that heap memory lives after the function ends.

int* thing () {
int my_array[3];
...
return my_array;
}

The above code is SUPER DANGEROUS and you should NEVER EVER DO IT because the next time you call a function, it's going to overwrite stack space and definitely overwrite the contents of my_array. You shouldn't return pointers to stack allocated data (or store it globally).
Essentially, all data that you allocated in a stack frame dies when the function returns.

However, you can do that with malloc(), as long as you remember to free() it eventually.

>>52221768
malloc isn't special, it's just a function that takes an input HOW MANY BYTES to alloc, and allocates that much.
Go read the fucking manual.


ALSO yall need to stop telling him it isn't valid; variable length stack arrays are completely valid on modern C compilers like GCC
>>
>>52221678
>stack and the heap
Memory allocated in the heap remains in existence for the duration of a program, so it's meant to be used to store global variables, and static variables.
The memory allocated in the stack area is used and reused during program execution, and will contain leftover values from allocating and deallocating memory from main() and subsequent functions().

You should read K&R.

https://wiki.installgentoo.com/index.php/Programming_resources#C

https://wiki.installgentoo.com/index.php/Programming_concepts
>>
>>52221812
>Go read the fucking manual.
myDick* array = malloc(n)

Is a valid code, when myDick is any struct I created before.
>>
The first one used to be illegal a long time ago, but for the past 20 years or so it's fine. Apart from that, the main difference between the two is stack vs. heap.
>>
>>52221845
Stop arguing with me.

Name

malloc, free, calloc, realloc - allocate and free dynamic memory

Synopsis

#include <stdlib.h>

void *malloc(size_t size);
void free(void *ptr);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);
Description

The malloc() function allocates size >bytes< and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().


If myDick is a struct with sizeof(myDick) = 8 bytes, and n is 3, then malloc(n) will return enough memory for 3 bytes even though you needed 24 for all three myDick structs.
>>
>>52221812
>ALSO yall need to stop telling him it isn't valid; variable length stack arrays are completely valid on modern C compilers like GCC
Actually VLAs are not part of the C11 spec, which is why LLVM only accepts them under very limited circumstances.

http://clang.llvm.org/compatibility.html
>>
>>52221745
Yeah, just use &variable_name to avoid passing it into functions by value (which makes a copy)

A dynamically allocated malloc/new doesnt have a variable name, but a pointer for access (funny enough, with C/C++ the variables are all pointers, anyhow), and will always be accessing that same copy, no duplicates will be made unless you choose to make a copy. When youre done, you use delete to take it off the heap.
>>
>>52221867
That's why it only works when you do it like
myDick* array = malloc(n)

It won't work if you do
myDick* array
-snip-
array = malloc(n)


Get out of DPT and stop arguing with me.
>>
>>52221885
Sure.

>>52221897
Prove it.
Also, this ain't DPT
>>
>>52221897
>That's why
What is it in the malloc man page that makes you think you're right?

Why would the behavior of malloc change between your two examples?
It will allocate n bytes in both cases.
>>
>>52222009
>Why would the behavior of malloc change between your two examples?
Not him, but why is
char string[100] = "OP Is a faggot"
valid whereas
char string [100]
random shit
string = "OP is a faggot"
not valid
>>
>>52221812
Can you explain better why that code is dangerous, please?
>>
>>52221885
>Actually VLAs are not part of the C11 spec
They are OPTIONAL to implement in C11. They are still there.
>>
>>52221678
>such advanced topics

is this what code boot camps lead to?
>>
>>52222054
Because you should use strcpy?
>>
>>52222054
http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#Arrays-as-Strings
>>
>>52222109
>They are OPTIONAL to implement in C11. They are still there.
Well yes, but they are optional for a reason, when before they were mandatory. They're slowly being phased out of existence.
>>
>>52222179
>They're slowly being phased out of existence
I'm pretty sure they made it optional because some people were whining about it being hard to implement.
The same for complex numbers.
>>
this get is dedicated to Guru.

RIP
>>
File: guru2.jpg (163 KB, 412x550) Image search: [Google]
guru2.jpg
163 KB, 412x550
>>52222209
this get is dedicated to Guru.

RIP

lowkey GOAT
>>
>>52222204
>I'm pretty sure they made it optional because some people were whining about it being hard to implement.
Do they really make anything easier though? I feel like it's just bloat.
>>
>>52222237
It helps you avoid unnecessary overhead by not allocating smaller shit on the heap.
>>
I didn't understand why this code is dangerous.

int* thing () {
int my_array[3];
...
return my_array;
}

Can anyone, kindly, explain it to me?
>>
>>52222478
my_array is no longer valid after you leave the function.
You should learn about the stack and stack frames.
>>
>>52222489
Oooh, yeah yeah! Now I got it.
It's because, being stored onto the stack, is automatically free-ed once outside its scope and so the address returned will point to garbage values outside that function.
Thank you.
>>
>>52222531
>It's because, being stored onto the stack, is automatically free-ed once outside its scope and so the address returned will point to garbage values outside that function.
Precisely.
>>
>>52221135
no it doesn't fuck you
variable length array declaration is part of the c99 standard

#include <stdio.h>

int main()
{
int n;
scanf("%d", &n);
int array[n];
}


is perfectly valid
>>
>>52222552
Thanks for pointing that out.
>>
>>52222552
>variable length array declaration is part of the c99 standard
Exactly, and it's being phased out by the new standard by now being 'optional'. It creates buffer overflows and alloca() is simply better.
>>
>>52222078
Simple explanation:
When a function returns, any data in it's "stack frame" becomes INVALID
e.g.
void my_function () {
// data in stack frame:
// variables:
int x, y;
char* a = NULL;

// arrays
int foo[5] = {0,1,5,2,3};
int bar[1024];
}

All of that data because invalid after the function returns. Invalid meaning you shouldn't use it.

int* bad_thing () {
int array[3];
return array;
}
void dangerous () {
int* a = bad_thing();
a[0] = 3;
}

You'll likely get a compiler warning for this, but in this case, "array" becomes invalid after bad_thing() returns, so trying to access its data in dangerous() is a bad idea. It's equivalent to doing:
int* worse_thing () {
int x = 3;
return &x;
}

The variable "x" is gone after the function returns, so the pointer you get points to somewhere completely unexpected.

I can give you an in-depth example of why it's bad and exactly what bad things can go wrong and why, if you'd like.
>>
>>52222834
Thank you. I got it.
>>
File: 1448193215817s.jpg (7 KB, 250x250) Image search: [Google]
1448193215817s.jpg
7 KB, 250x250
>>52222114

that's right
>>
>>52222912
Just a clarification: the term "heap" here is not used as in [here](https://en.wikipedia.org/wiki/Heap_(data_structure)), right?
>>
>>52223122
no
https://en.m.wikipedia.org/wiki/Dynamic_memory_allocation#DYNAMIC
>>
>>52223240
Perfect. Thanks a lot, again (if you're the same person (: ) !
Thread replies: 57
Thread images: 3

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.