I'm starting off in C programming, and I'm currently studying structures and using pointers to work with them. I've been trying to write a simple program which stores your personal details (name and birthday) for practice, but I've been having trouble with memory allocation and I'm clearly missing something - so I tried something simpler, and apparently I'm having trouble with allocating memory for the string. I've tried my best at debugging this, but I've no clue what's wrong.
#include<stdio.h>
#include<stdlib.h>
#include<stddef.h>
#include<string.h>
int main()
{
char DummyString[100];
printf("Enter a string to be read back to you: ");
scanf("%s",&DummyString);
printf("The string is: %s\n",DummyString);
printf("String length is %d\n",strlen(DummyString));
printf("sizeof char is %i\n",sizeof(char*));
// char DumbStringPtr=&DumbString;
char *DummyStringPtr = (char*)malloc((sizeof(char))*(strlen(DummyString)+1)); // returns 8 regardless of anything
printf("The size of the pointer would be %d\n", sizeof(DummyStringPtr));
}
In the original program, the failure was after trying to copy a string into the allocated pointer, which I'm assuming is due to shortage of memory (will show code if necessary). I feel like I've missed something fundamental and so would appreciate any feedback. I'd really appreciate it if someone can give me a lead on my mistake. Thanks!
scanf("%s",&DummyString);
is wrong. Since DummyString
is an array, you get a pointer to its first element when you use it in an expression, and that's what scanf expects. Change to scanf("%s",DummyString);
.char *DummyStringPtr = malloc(strlen(DummyString)+1));
sizeof
will not tell you how much memory you have allocated. You have to keep track of this yourself, in a separate size variable if needed.sizeof
is %zu
since sizeof
returns type size_t
. Quick & dirty version for newbies is to use printf("%d", (int)sizeof(something));
free(DummyStringPtr);
.