473,836 Members | 1,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamically Allocated Memory vs. Statically allocated Memory

I have a really simple question.
What is the difference between allocating memory following way:

#1
int main(int argc,char* argv)
{
char str[strlen(argv[1])+1];
return 0;
}

vs.

#2
int main(int argc,char* argv)
{
char* str=malloc(strl en(argv[1])+1);
return 0;
}

Both code compiles fine on a Linux machine, but code #2 fails with
visual C++ compiler.

Is the code #1 not safe??? or there is not a huge difference between
the code and it is just a compiler issue? ( I understand that in code
#2 the memory is located on heap as oppose to the code #1)
Any help, regarding this would be greatly appreciated!

Jul 22 '05 #1
5 2374
<cs****@gmail.c om> wrote...
I have a really simple question.
What is the difference between allocating memory following way:

#1
int main(int argc,char* argv)
{
char str[strlen(argv[1])+1];
return 0;
}

vs.

#2
int main(int argc,char* argv)
{
char* str=malloc(strl en(argv[1])+1);
return 0;
}

Both code compiles fine on a Linux machine, but code #2 fails with
visual C++ compiler.
I actually expect the #1 to fail. It is not a valid C++ program. Array
size has to be compile-time constant.
Is the code #1 not safe???
Code #1 is not valid.
or there is not a huge difference between
the code and it is just a compiler issue? ( I understand that in code
#2 the memory is located on heap as oppose to the code #1)
Any help, regarding this would be greatly appreciated!


See above.

V
Jul 22 '05 #2
cs****@gmail.co m wrote:
I have a really simple question.
What is the difference between allocating memory following way:

#1
int main(int argc,char* argv)
{
char str[strlen(argv[1])+1];
return 0;
}

vs.

#2
int main(int argc,char* argv)
{
char* str=malloc(strl en(argv[1])+1);
return 0;
}


Both pieces of code should fail. The footprint of main is

int main(int argc, char *argv[])
^^

You are declaring argv as a pointer, not as an array of pointers.

Jul 22 '05 #3
cs****@gmail.co m wrote:
I have a really simple question.
What is the difference between allocating memory following way:

#1
int main(int argc,char* argv)
{
char str[strlen(argv[1])+1];
return 0;
}

vs.

#2
int main(int argc,char* argv)
{
char* str=malloc(strl en(argv[1])+1);
return 0;
}


Another alternative:
int main(int argc, char * * argv)
{
char * str = new char [strlen(argv[1]) + 1];
return 0;
}

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Jul 22 '05 #4
Thomas Matthews wrote:
cs****@gmail.co m wrote:
I have a really simple question.
What is the difference between allocating memory following way:

#1
int main(int argc,char* argv)
{
char str[strlen(argv[1])+1];
return 0;
}

vs.

#2
int main(int argc,char* argv)
{
char* str=malloc(strl en(argv[1])+1);
return 0;
}

Another alternative:
int main(int argc, char * * argv)
{
char * str = new char [strlen(argv[1]) + 1];
return 0;
}


Speaking of alternatives, I'd recommend

#include <string>
int main(int argc, char **argv)
{
if (argc > 1) {
std::string str(argv[1]);
// whatever else
}
return 0
}

otherwise if the program is run without additional arguments, argv[1]
is NULL and strlen(NULL) has undefined behaviour.

V
Jul 22 '05 #5
<cs****@gmail.c om> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
I have a really simple question.
What is the difference between allocating memory following way:

#1
int main(int argc,char* argv)
{
char str[strlen(argv[1])+1];
return 0;
}

vs.

#2
int main(int argc,char* argv)
{
char* str=malloc(strl en(argv[1])+1);
return 0;
}

Both code compiles fine on a Linux machine, but code #2 fails with
visual C++ compiler.

Is the code #1 not safe??? or there is not a huge difference between
the code and it is just a compiler issue? ( I understand that in code
#2 the memory is located on heap as oppose to the code #1)
Any help, regarding this would be greatly appreciated!


As others have mentioned, #1 is actually not valid code (you need to have a
constant size when statically declaring/allocating an array).

When you say #2 'fails', do you mean fails to compile or fails at runtime?
I assume the former. I tried compiling under VC6 and got a compile error
about strlen being unable to convert from char to const char *. Remember
that argv is actually a char**, not a char*. Also, malloc returns a void*,
you need to cast that to a char* for your assignment to 'str' to work (i.e.
compile).

-Matt
Jul 22 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2094
by: kk | last post by:
Hi all, i didn't get output in the following code while compiling and executing with g++ version 3.2.3 it doesn't allocate memory to pointer varaible (x) in class B. and it gives correct output while executing in .Net and visual slick editor. why it didn't allocate memory? if anybody knows plz give reply. thanks in advance kk
4
3869
by: Thomas Paul Diffenbach | last post by:
Can anyone point me to an open source library of /statically allocated/ data structures? I'm writing some code that would benefit from trees, preferably self balancing, but on an embedded system that doesn't offer dynamic memory allocation (to be clear: no malloc, no realloc), and with rather tight memory constraints. Writing my own malloc to do dynamic allocation from some static pool isn't really an option, for various reasons, not...
3
9598
by: Justin To via AccessMonster.com | last post by:
I just distributed a FE mde file throught my department, and while stress testing on the performance of the new release, 3 users got the following error: The instruction at ... referenced memory at ... The memory cannot be "read". this seems like a computer-local problem as I cannot reproduce the same error on any other computers I tried running Dr. Watson (win2k) and it says "Exception number: c0000005
10
2787
by: s.subbarayan | last post by:
Dear all, I happen to come across this exciting inspiring article regarding memory leaks in this website: http://www.embedded.com/story/OEG20020222S0026 In this article the author mentions: "At a certain point in the code you may be unsure if a particular block is no longer needed. If you free() this piece of memory, but continue to access it (probably via a second pointer to the same
0
808
by: menkaur | last post by:
Is there eny way to get the memory size allocated with new (like GlobalSize for GlobalAlloc) ?
4
1126
by: Julián Sanz García | last post by:
Hi!!, How can i use Ram memory or virtual memory to crear a file??? The idea is to create a file in a temporaly space, something like RAM memory or virtual memory. Thanks
3
1432
by: Sakharam Phapale | last post by:
Hi All, How to get the no of memory bytes allocated to the Array of type String? Dim arrDetail(100,10) As String Thanks and Regards Sakharam Phapale
11
2647
by: mast2as | last post by:
This question has been posted to this forum before and I read the thread but found that the answers were perhaps imcomplete, so I am trying again. Whenever I am creating objects I would like to keep track of the memory which is used for each object (for stats purpose). They are 2 basic approaches, one is to write a Memory manager type of class where new & delete would be overloading the standard new & delete operator. Each time the new...
2
1383
by: nguyenlh | last post by:
I'm studying about Memory managerment - stack memory and I can't understand the following problems : Who can help me >> - Role of Stack memory -How to store address in stack memory -Garbage collection process in stack memory -Reuse and access address in stack memory I'm a newbie >>> Thanks very much...
0
10852
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10596
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10255
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9382
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4459
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4021
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3116
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.