1

I find some answers but they all work on Linux only. But how about MacOS? My code is okay on ubuntu so I needn't paste them on. Thank you! ———————————————————————————————————————————— Revise and paste my code.

void unix_error(char* msg)
{
    fprintf(stderr, "%s: %s\n", msg, strerror(errno));  
    exit(0);
}
void* Mmap(void* start, size_t length, int prot, int flags, int fd, off_t offset)
{
    void* ptr;
    if((ptr = mmap(start, length, prot, flags , fd, offset)) == ((void*)-1)){
        unix_error("mmap");
    }
    return ptr;
}

int main
{
    char *homepath = getenv("HOME");
    char *file = "/Desktop/main.c"; 
    strcat(homepath, file);
    printf("%s\n", homepath);
    int fd = open_file(homepath);
    printf("%d\n", fd);
    char *ptr = Mmap(NULL, filesize, PROT_READ, MAP_PRIVATE, fd, 0);
    write(1, ptr, filesize);
}

get error:

/Users/<username>/Desktop/main.c
3
mmap: Cannot allocate memory
wind2412
  • 1,011
  • 1
  • 9
  • 24
  • 1
    Please show your code so we can see what you're trying to do. – STLDev Jan 29 '17 at 09:29
  • code added.@STLDeveloper – wind2412 Jan 29 '17 at 09:35
  • That's obviously not the code that madethis message. Please show us all code needed to replicate your issue. – fuz Jan 29 '17 at 09:36
  • @fuz added. But not the code's reason. Because in 64bit Ubuntu it ran perfectly. – wind2412 Jan 29 '17 at 09:41
  • @wind2412 Even if code runs on one platform, with one compilers etc doesn't mean the code is not wrong. The moment you realize that you wil have much easier time handling errors. You should look into *undefined behaviour* for starters to understand this concept. – Sami Kuhmonen Jan 29 '17 at 09:44
  • @SamiKuhmonen Yeah. So I comiled my code by clang and gcc but... also this problem. – wind2412 Jan 29 '17 at 09:50
  • @SamiKuhmonen like this. http://stackoverflow.com/questions/27634109/why-mmap-cannot-allocate-memory .The same problem. – wind2412 Jan 29 '17 at 09:52
  • 2
    Your `strcat(homepath, file);` is problematic as `gwtenv()` typically returns a pointer to memory that you definitely should not be appending to. – John Hascall Jan 29 '17 at 10:08
  • @JohnHascall Oh gosh. You're right. Thx. After changing the 'file' I got the real output. – wind2412 Jan 29 '17 at 10:12

1 Answers1

1

The getenv() function typically returns a pointer to memory you can't / shouldn't modify. And it most assuredly doesn't return one with a bunch of extra space on the end that you can append to.

So your strcat(homepath, file) is trampling over memory it shouldn't and so anything can happen after that. It might (appear to) work correctly, it might fail immediately or considerably later, or it even might expel monkies from your exhaust port.

John Hascall
  • 9,176
  • 6
  • 48
  • 72