-1
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <conio.h>

void main(){
    void generateId(char*, char*);

    char name[20];
    char id[7];
    printf("Enter your name: ");
    scanf("%s", name);
    generateId(name, id);

}

void generateId(char *name, char *id){

    char *ptrName = name;
    char *ptrId = id;
    puts(ptrName);//crashes if i used puts(*ptrName);
}

can someone explain to me the above commented line? why does the program crash giving a valid input of less than 20 , if i try to dereference the pointer? but instead it didn't crash when i didnt dereference the pointer. shouldn't it give me the value that i entered if i dereferenced it? but how come it gives me the value if i didn't dereference it?

1

2 Answers 2

1

Function puts expects the address of a null-terminated string in memory.

In your code, variable ptrName is indeed pointing to a null-terminated string in memory.

But by calling puts(*ptrName), you are passing the first character of that string instead.

When passed to function puts, the value of that character is expanded to the size of an address (typically 4 or 8 bytes), and the function assumes that is is pointing to a valid null-terminated string.

The function then attempts to read the contents at that memory address, which most likely yields an illegal memory access (although officially it is considered undefined behavior - anything can happen).

2
  • "Function puts expects the address of a null-terminated string in memory." from where can i read about specific C function details such as the one you have written?
    – sutoL
    Nov 16, 2014 at 16:11
  • 1
    @sutoL: Open google.com, type puts in the search-box, click enter, wait until you are redirected to a new web-page with a list of web links, choose the first non-commercial link and open it. Nov 16, 2014 at 16:14
1

ptrName is a pointer to char. *ptrName is char. The function puts takes pointer as a parameter, not char. When you use it like this, it will try to interpret the Char's value as a pointer an will cause a memory violation.

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