[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 197
  • Last Modified:

newbie needs help on easy one

I am new to C and have written a simple program ( added below) that receives a string allocates address to a pointer
allocates memory to the string accordingly and is supposed to print the string. I think I did everythig right so why does it print garbage instead of the string ???
0
bitman
Asked:
bitman
1 Solution
 
tatoCommented:
Excuse my english
Add like a comment a simple program
0
 
snifongCommented:
Post the code.
0
 
rbrCommented:
Where is the code?
0
Will You Be GDPR Compliant by 5/28/2018?

GDPR? That's a regulation for the European Union. But, if you collect data from customers or employees within the EU, then you need to know about GDPR and make sure your organization is compliant by May 2018. Check out our preparation checklist to make sure you're on track today!

 
cgallagherCommented:
Its possible that it hasn't been initialised with a NULL value at the last character, but would need the code to verify.
If this is the problem then the code could be something like

myarr[10] = '\0';

10 being the last value of the array.
0
 
deightonCommented:
You need to allocate the memory before you put the string in it.  

0
 
deightonCommented:
You had the right idea checking the pointer for NULL after malloc, but the code was in the wrong order, you needed to malloc then gets

#include <stdio.h>
                   #include <string.h>
                   #include <stdlib.h>
                   void main()
                   {
                   char *ptr,str[20];
                   ptr = str;

                 
                   ptr = (char*)malloc(strlen(ptr)+1);
                   if(ptr == NULL)
                   {
                   printf("memory allocation failure");
                   return;
                   }

                   printf("Please enter a string  >:");
                   gets(ptr);
                   printf("%s\n\n",ptr);
                   }

Basically *ptr comes into existence without any reserved memory.  When you use it in gets you put the string in uninialised memory.  when you use 'malloc' them memory is allocated somewhere else and *ptr points to this memory somewhere else.  The allocated memory isn't initialised, its just left as junk until you do something with it.
0
 
bitmanAuthor Commented:
Hi Deighton

I'm a bit confused. If we malloc before gets it would mean that we are mallocing the pointer itself. In the case of my program is it worth mallocing the pointer as from what I understand one pointer is a fixed 2 or 4 bytes. I can understand mallocing an array of pointers before gets but not a single pointer.
Also the string itself, surely this can only be malloced the gets, else how does the compiler know the strlen ?
I actually succeed
Please clarrify,

thanks for everything
Bitman
0
 
C_DreamerCommented:
0 points? Cool! I could do with zero points...

It is interesting that this answer (below) was accepted. Let's have a look at what's wrong with it:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()

main returns int, not void. Any other return type, and you're no longer programming in C, but in some bizarre concoction of your own.

{
char *ptr,str[20];
ptr = str;

This assignment is fine, but pointless, as the value of ptr is about to be overwritten immediately.
                  
tr = (char*)malloc(strlen(ptr)+1);

Firstly, at this point, str's contents are uninitialised, so the amount of memory allocated here is more or less random.

Secondly, why the cast? It's completely unnecessary. If your compiler gives you a diagnostic for it, you're not using a C compiler (in C++, the cast IS required, and some editors save as .cpp rather than .c if you are not firm with them).

 if(ptr == NULL)
 {
   printf("memory allocation failure");
   return;

main returns int. This should be return EXIT_FAILURE;

}

printf("Please enter a string  >:");

If you want to /ensure/ that this output appears in time for the user, either add a \n to the end of the prompt, or call fflush(stdout);

 gets(ptr);

gets() is a bug waiting to happen. Don't /ever/ use it. It doesn't protect its buffer against overflow.

Use fgets() instead. Note that, for fgets, you will need a decent buffer, not one that has a random size, such as in this program.

 printf("%s\n\n",ptr);

If you fix everything else that's wrong with this program, this printf should work just fine. :-)

  Once you're done with memory, it's a good plan to free it up. One day, this bit of defensive programming will save you a LOT of problems. (I speak from bitter experience here.)

  free(ptr);

Because main returns int, you should add

  return 0;

or

  return EXIT_SUCCESS;

Either will do.

}

I am deeply concerned that you accepted this answer, as it had more bugs in it than an ant farm.

There is something amiss with a system which allows such answers to be accepted.
0

Featured Post

Choose an Exciting Career in Cybersecurity

Help prevent cyber-threats and provide solutions to safeguard our global digital economy. Earn your MS in Cybersecurity. WGU’s MSCSIA degree program was designed in collaboration with national intelligence organizations and IT industry leaders.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now