0

I try to allocate memory , store a string then print it but I think it didn't work.

#include<stdio.h>
#include<windows.h>
int main()
{
    char* allochere;
    allochere = malloc(sizeof(char));
    *allochere = "Hello";
    printf("%s",allochere);


    return 0;
}
1
  • 1) "sizeof(char)" is always 1. You don't need it, you don't want it. Specify an ACTUAL length instead. 2) The length for "Hello" would be 6: H, e, l, l, o, \0: allochere = malloc(6); 3) Use strcpy() to copy "Hello" into allochere. A simple assignment just sets the pointer value, not the contents of the string.
    – paulsm4
    Oct 4, 2013 at 22:51

6 Answers 6

3

The assignment to *allochere only assigns a value to the first character of the uninitialized string. The value assigned is nonsensical to boot, since the right-hand side of the assignment is a pointer. (If you turn on compilation warnings, the compiler will warn you of problems with such an assignment.)

To correctly initialize the string, you need to call strcpy to copy the string:

strcpy(allochere, "Hello");

Also, you need to allocate allochere with the correct size to hold the string you intend to put there:

allochere = malloc(strlen("Hello") + 1);
1
  • Correct me please if I'm wrong : *allochere is a dereferenced pointer to char ... allochere is a pointer to the allocated memory ... &allochere is the address of allochere ! Oct 4, 2013 at 22:44
2

That code doesn't make any sense.

char *allochere;

'allochere' is a pointer to a char, in other words, a string.

allochere = malloc(sizeof(char));

Now you allocate a single character, and point 'allochere' to that. BTW, sizeof(char) is always 1.

*allochere = "Hello";

Now you set the first char of 'allochere' to a 'const char *', a compiler would barf here. Now allochere points to random data, not a string.

Let's see some alternatives that work.

char *allochere;
allochere = "Hello";
printf("%s", allochere);

char *allochere;
allochere = strdup("Hello");
printf("%s", allochere);

char *allochere;
allochere = malloc(strlen("Hello") + 1);
strcpy(allochere, "Hello");
printf("%s", allochere);
1
  • Please mention that strdup() contains an implicit malloc(). The returned char* must be free()d, just like any other heap-allocated memory. Oct 4, 2013 at 23:29
2

There are several mistakes here.

First of all, you should know that C-strings end with a zero byte. Thanks to this, you don't have to store string's length, you're just saying "here's the end of my string" using the zero byte.

Secondly, you call malloc() in a wrong way. If you want to allocate memory for an N-letter string, you should write malloc(N + 1); (+1 because the zero byte has to have its cell, too).

Lastly, you should use a function like strcpy to copy the string to its destination. In this case, you should call strcpy(allochere, "Hello").

Your code should look like this:

char* allochere;
allochere = malloc(6*sizeof(char));
strcpy(allochere, "Hello");
printf("%s", allochere);

...

// don't forget to deallocate the memory
free(allochere);
3
  • "you should write (char*)malloc(N + 1);" No. You should write malloc(N + 1);" without the error-hiding (char*).
    – glglgl
    Oct 4, 2013 at 22:46
  • There is one more potential mistake. The allocated memory is not explicitly free()d after use, so there is a potential for a memory leak, expecially if this code is copied somewhere else. While this is OK in this example - it is implicitly free()d when main() returns - it is bad practice in general and any static analyser worth its salt should flag it. Oct 4, 2013 at 23:34
  • @DigitalTrauma, you're right, I'll add to make the example complete.
    – PiotrK
    Oct 4, 2013 at 23:48
1

You need something like this.

#include<stdio.h>
#include<windows.h>

int main()
{
    char* allochere;

    allochere = malloc(strlen("Hello") + 1);

    strcpy(allochere, "Hello");
    printf("%s\n", allochere);

    return 0;
}
5
  • 2
    why #include <windows.h>? Oct 4, 2013 at 22:45
  • Under unix/linux/bsd systems, we would normally include <stdlib.h> to pick up declaration for malloc. With windows, all bets are off. It does things 'differently'. I just assumed, perhaps incorrectly, that <windows.h> is where malloc is declared. Oct 4, 2013 at 22:57
  • The OP didn't mention Windows in the question. But even if he did, I don't follow your reasoning. Windows does do many things differently than Unix, but it does support compilers that support standard C functions malloc, strcpy, and printf without resorting to platform-specific headers. Have you tried simply including <stdlib.h>? Oct 4, 2013 at 23:13
  • The only reason I included <windows.h> is because the original post has it at line 2. I assumed that the original poster had a good reason for doing it. I am currently not logged into my windows system and can't verify whether <stdlib.h> will just work. Can't think of a reason why it wouldn't work if it exists. <windows.h> pulls in a lot of things and it may include <stdlib.h>. Oct 4, 2013 at 23:26
  • Since the OP is obviously a beginner, I'd say the assumption is flawed. :) Oct 5, 2013 at 5:40
1

You are not allocating enough memory to hold the word "Hello" - you need to allocate space for 5 chars plus the terminating byte, so you should replace the malloc call with:

allochere = malloc(6);

You can't assign a string literal to allochere because you will miss the pointer to the allocated memory. Instead, after allocating enough space, use strcpy:

strcpy(allochere, "Hello");
3
  • Side note: sizeof(char) is always 1; malloc(sizeof(char)) is the same as malloc(1). Oct 4, 2013 at 22:42
  • 1
    Why do you recommend the casting of malloc()'s return value? It is common sense that it is bad.
    – glglgl
    Oct 4, 2013 at 22:49
  • Good point. I don't exactly recommend it, it's just the force of habit. I'll just remove it from my code sample, as it is clearly not good advice. Thanks for the heads up ;) Oct 4, 2013 at 23:11
0

In this case, you need to actually copy the data directly from the string constant "Hello" into your allocated space. However, before we even get there, there are a couple of issues.

  1. Make sure you're allocating enough space.

    You are allocating the sizeof one character, not enough to hold the entire string (5 characters in "Hello" plus one more for the null terminator). You can do this with

    allochere = malloc(6);
    

    or use the common convention of

    allochere = malloc(strlen("Hello") + 1);
    

    To be more clear about the size and purpose you're allocating the memory for.

  2. You need to copy the data because string assignment doesn't understand exactly what you're trying to do. By doing

    *allochere = "Hello";
    

    You're actually assigning the value at allochere to be the address of "Hello". If instead you had done this:

    allochere = "Hello";
    

    That might actually work (on some systems -- I'm not sure and haven't tested it), but that's because you are assigning and address to an address.

    However, you are mallocing data which means you want to copy the data. Thus, you will want to use something like strcpy to copy from the location into your allocated string. Hence:

    strcpy(allochere, "Hello");
    
  3. The last problem is going to be actually seeing the output. Because you're using printf, you will need to flush the data to the screen. printf will automatically flush the data if you have a newline ('\n') character, but you could also use fflush().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.