This question already has answers here:
What is the trick behind strcpy()/uninitialized char pointer this code?
(3 answers)
Closed 5 years ago.
Why this code compile but not running?
int main() {
char *s;
scanf("%15s", s);
puts(s);
}
Because s is an uninitialized pointer, you cannot store data there (since there "is no there there").
Try:
char s[32];
instead, that gives you 32 characters' worth of room into which scanf() can write.
You need to provide memory for scanf(...) The char *s is only a pointer to some memory, but not he memory itself. You can either malloc(...) the memory and have s point to it, or allocate it locally on the stack by char s[16]
For starters, provide a proper buffer to the scanf call. For example, instead of char *s which is simply an uninitialized pointer, try char s[128].
Related
This question already has answers here:
Sprintf Segmentation Fault
(5 answers)
Closed 5 years ago.
why is the the second sprintf not working?
char* jc;
char* tn;
char* result = malloc((256)*sizeof(char));
int thread=99;
int jobcounter=88;
sprintf(jc, "%d", jobcounter);
sprintf(tn, "%d", thread);
strcpy(result,"file_");
strcat(result,jc);
strcat(result,"_");
strcat(result, tn);
strcat(result,".html");
printf("%s",result);
Output:
file_88_Þ*m.html
In your case
sprintf(jc, "%d", jobcounter);
sprintf(tn, "%d", thread);
causes undefined behavior as none of those pointers (first arguments) point to any valid memory.
You need to make sure that the pointer(s) you're using to access a(ny) memory location points to a valid memory. You can either
make them point to statically/automatic allocated variable or
use a memory allocator function like malloc() or family.
This question already has an answer here:
Is modification of string literals undefined behaviour according to the C89 standard?
(1 answer)
Closed 7 years ago.
So I've been playing around with C lately and have been trying to understand the intricacies of passing by value/reference and the ability to manipulate a passed-in variable inside a function. I've hit a road block, however, with the following:
void modifyCharArray(char *input)
{
//change input[0] to 'D'
input[0] = 'D';
}
int main()
{
char *test = "Bad";
modifyCharArray(test);
printf("Bad --> %s\n", test);
}
So the idea was to just modify a char array inside a function, and then print out said array after the modification completed. However, this fails, since all I'm doing is modifying the value of input that is passed in and not the actual memory address.
In short, is there any way I can take in a char *input into a function and modify its original memory address without using something like memcpy from string.h?
In short, is there any way I can take in a char *input into a function and modify its original memory address without using something like memcpy from string.h?
Yes, you can. Your function modifyCharArray is doing the right thing. What you are seeing is caused by that fact that
char *test = "Bad";
creates "Bad" in read only memory of the program and test points to that memory. Changing it is cause for undefined behavior.
If you want to create a modifiable string, use:
char test[] = "Bad";
This question already has answers here:
Returning an array using C
(8 answers)
Closed 8 years ago.
I have an idea on dangling pointer. I know that the following program will produce a dangling pointer.But I couldnt understand the output of the program
char *getString()
{
char str[] = "Stack Overflow ";
return str;
}
int main()
{
char *s=getString();
printf("%c\n",s[1]);
printf("%s",s); // Statement -1
printf("%s\n",s); // Statement -2
return 0;
}
The output of the following program is
t
if only Statement-1 is there then output is some grabage values
if only Statement-2 is there then output is new line
Your code shows undefined behaviour, as you're returning the address of a local variable.
There is no existence of str once the getString() function has finished execution and returned.
As for the question,
if only Statement-1 is there then output is some grabage values if only Statement-2 is there then output is new line
No explanations. Once your program exhibits undefined behaviour, the output cannot be predicted, that's all. [who knows, it might print your cell phone number, too, or a daemon may fly out of my nose]
For simple logical part, adding a \n in printf() will cause the output buffer to be flushed to the output immediately. [Hint: stdout is line buffered.]
Solution:
You can do your job either of the two ways stated below
Take a pointer, allocate memory dynamically inside getString() and return the pointer. (I'd recommend this). Also, free() it later in main() once you're done.
make the char str[] static so that the scope is not limited to the lifetime of the function. (not so good, but still will do the job)
your str in getString is a local variable, which is allocate on stack, and when the function returns, it doesn't exist anymore.
I suggest you rewrite getString() like this
char *getString()
{
char str[] = "Stack Overflow ";
char *tmp = (char*)malloc(sizeof(char)*strlen(str));
memcpy(tmp, str, strlen(str));
return tmp;
}
and you need to add
free(s);
before return 0;
In my case, pointer tmp points to a block memory on heap, which will exist till your program ends
you need to know more about stack and heap
Besides, there is still another way, use static variable instead
char *getString()
{
static char str[] = "Stack Overflow ";
return str;
}
PS: You get the correct answer for the following statement printf("%c\n",s[1]); is just a coincidence. Opera System didn't have time to do some clean work when you return from function. But it will
Array is returned as a pointer yet the array itself is the garbage after return from function. Just use static modifier.
What's concerning s[1] is OK. The point is, it's the first printf after getting the dangling pointer. So, the stack at this point is still (probably) intact. You should recall that stack is used for function calls and local variables only (in DOS it could be used by system interrupts, but now it's not the case). So, before the first printf (when s[1] is calc'ed), s[] is OK, but after - it's not (printf' code had messed it up). I hope, now it's clear.
This question already has answers here:
why scanf scans a null value
(2 answers)
Closed 8 years ago.
I'm sure there just a silly mistake here, however, I can't figure it out.
This is part of my code:
char *moving;
scanf("%s", moving);
When I compile it with gcc, it says the following:
newmatrix.c:38:7: warning: ‘moving’ is used uninitialized in this function [-Wuninitialized]
Line 38 is the scanf
How do I fix this?
Thanks
You can allocate memory before you call scanf(). For example:
char moving[256];
if (scanf("%255s", moving) != 1)
…oops — presumably EOF…
You could use malloc() instead of a simple array, but then you have to remember to free the allocated memory. OTOH, if you want to return the data from the function where it is read, it may well be more convenient to use malloc(), but consider passing a pointer to the space (and its size?) to the function.
Or you can have scanf() do the memory allocation for you (check the manual page for scanf() carefully — read it weekly until you've memorized (enough of) it):
char *moving;
if (scanf("%255ms", &moving) != 1)
…oops — probably EOF, but perhaps OOM (out of memory)…
…use moving…
free(moving);
Yes, this is one of the lesser-known options in POSIX-standard scanf(); it is not a part of Standard C.
Allocate memory for moving before using it. Use malloc().
moving is pointer of char type. Before storing the string in moving, you need to allocate memory for it.
char *moving;
moving = malloc(100);
scanf("%s", moving);
OR
Simply change char *moving to char moving[256].
Also instead of scanf() use fgets().
allocate memory to the pointer before using it
char *moving;
moving = malloc(100*sizeof(char));
scanf("%s", moving);
This question already has answers here:
C segmentation fault-char pointers
(3 answers)
Closed 8 years ago.
I'm new in learning the C-Language and I have a question to pointers.
For Example if I try this:
char *pointer;
strcpy(pointer,"Hello, World!\n");
printf(pointer);
I get this Output:
Segmentation Fault
But if I try this:
char *pointer = "Hello, World!\n");
printf(pointer);
I get this:
Hello, World!
My question is why it isn't working with strcpy.
The functions do the same overall.
What is the difference between the first sourcecode and the second?
It would be good if someone could explain what is happening in the memory, so that I can get a better view at this.
char* pointer merely gives you a variable to use to access the memory location. You've not yet allocated any memory, so when you do the strcpy you're writing to whatever random/undefined value pointer has.
You need to do something like:
char* pointer = calloc(LEN);
if (pointer)
{
strcpy(pointer, "Hello World");
printf(pointer);
free(pointer);
}
The first parameter to "strcpy" should be pointing to a usable location in memory. In your first source code, you havent initialized "pointer" to anything. You should first initialize it, for example by declaring it to be an array of characters of maximum length:
char myArray[42]; // where 42 represents the maximum capacity